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 }
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\\"
Setting\\ 開啟Setting資料夾,此時會看到Setting資料夾內的檔案.
取得桌面的路徑:
openFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
C:\app
-example.exe
-Setting
C:\app\Setting
-set1.txt
-set2.txt
沒有留言:
張貼留言