2018年9月15日 星期六

[C#] .txt檔存取及讀寫

1.載入.txt檔案
OpenFileDialog openFileDialog1 = new OpenFileDialog();

/*Sets the file dialog box title.*/
openFileDialog1.Title = "Select *.txt";

/*Sets the initial directory displayed by the file dialog box.*/
openFileDialog1.InitialDirectory = "..\\Setting\\";

/*Sets the current file name filter string.*/
openFileDialog1.Filter = "dat files (*.*)|*.txt";

/*Runs a common dialog box with a default owner.*/
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
     /*Provides a Stream for a file*/
     FileStream filestream = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read);

     /*Initializes a new instance of the StreamReader class for the specified stream.*/
     StreamReader sr = new StreamReader(filestream);

/*選一種方式讀出*/
#if(true)
     /*一次讀完全部*/
     textBox1.Text = sr.ReadToEnd();
#else
     /*一次讀一行*/
     string line;
     int lineCounter = 0; 

     while((line = sr.ReadLine()) != null)  
     {  
          textBox1.Text += line;
          
          /*計算總共有幾行*/
          lineCounter++;
     } 
#endif
}

2.清除載入的.txt內容 
FileStream filestream = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Write);
filestream.SetLength(0);//Clear
filestream.Close();


3.儲存.txt檔案 
   string tmpString = "Eaxmple";

   SaveFileDialog saveFileDialog1 = new SaveFileDialog();

   saveFileDialog1.InitialDirectory = "..\\Setting\\";
   saveFileDialog1.Title = "Select *.txt";
   saveFileDialog1.Filter = "dat files (*.*)|*.txt";

   if (saveFileDialog1.ShowDialog() == DialogResult.OK)
   {
      FileStream filestream = new FileStream(saveFileDialog1.FileName, FileMode.OpenOrCreate, FileAccess.Write);
      StreamWriter sw = new StreamWriter(filestream);
      sw.Write(tmpString);
      sw.Close();
   }

-------
預設路徑設定:
若預設要選取Setting資料夾內的檔案

openFileDialog1.InitialDirectory = "..\\Setting\\"

..\\  到目前目錄之同級目錄中檔案的相對路徑,意思是會到example.exe的這個目錄.
Setting\\  開啟Setting資料夾,此時會看到Setting資料夾內的檔案.

取得桌面的路徑:
openFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

C:\app
-example.exe
-Setting

C:\app\Setting
-set1.txt
-set2.txt





沒有留言:

張貼留言