2013-08-16 54 views
1

我正在開發一個c#應用程序。在這個表格中,我添加了2個按鈕。 這些是BrowseCreate File按鈕。在c#應用程序的選定位置創建txt文件

現在我想要做的就是使用瀏覽按鈕來瀏覽一個位置,然後單擊Create file按鈕時,在該位置創建一個文本文件。

+0

是winforms還是wpf? – wudzik

+0

你確定你想要兩個按鈕嗎?應用程序具有單獨的「設置文件位置」和「保存」操作是很少見的。 –

+0

@wudzik - 它的窗體形式 – amila

回答

4

看一看

SaveFileDialog Class

提示用戶選擇用於保存文件的位置。

FolderBrowserDialog Class

提示用戶選擇文件夾。

File.Create Method

創建指定路徑的文件中。

甚至

File.CreateText Method

創建或打開一個文件上單擊事件編寫UTF-8編碼的文本

+0

我試過SaveFileDialog。但我無法選擇文件夾位置。瀏覽時,它要求文件選擇位置。 – amila

+0

@amila - 然後你需要['FolderBrowserDialog'](http://msdn.microsoft.com/en-us/library/system.windows.forms.folderbrowserdialog.aspx)。 –

2

做這樣的

//if you want to overwrite the file if it already exists you can bypass this check 
if (File.Exists(path)) 
{    
     File.Delete(path); 
} 

     // Create the file. 
     using (FileStream fs = File.Create(path)) 
     { 
      Byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file."); 
      // Add some information to the file. 
      fs.Write(info, 0, info.Length); 
     } 

如果你不打算寫任何東西

FileStream fs = File.Create(path); 
fs.Close(); //this needs to be done 

你需要閱讀this

+0

如果文件不存在,文件刪除不會引發錯誤,不需要檢查它 – Sayse

+0

如果用戶想要創建一個新文件而不是覆蓋它,該怎麼辦? – Ehsan

+0

我不是說不要使用delete,我是說,刪除不執行任何操作,如果文件不存在 – Sayse

相關問題