2014-10-10 40 views
0

我想知道你是否可以幫我解決這個問題。我有一個DataGridView與保存在其上的幾本書。當我點擊一本書時,這本書的故事載入RichTextBox。當我更改該文本並想保存它時,我想將內容保存在.txt文件中。我怎麼去解決它?以.txt格式保存文件(記事本)

我已經包含代碼供您查看我想要做什麼。

string FileLine = ""; 
StreamWriter OutputFile; 
foreach (Book book in myBookList) 
{ 
    //Book Book = new Book(); 
    Book nBook = myBookList[dgv.CurrentCell.RowIndex]; 
    //PROBLEM IS HERE 
    OutputFile = new StreamWriter(nBook.TxtFileName); 
    //------------------------------------------------------------- 
    //I want it to be something like this: {nBook.TxtFileName}.txt 
    //------------------------------------------------------------- 
    //Code to write data to file 
    OutputFile.WriteLine(FileLine); 
    OutputFile.Close(); 
} 

感謝 :)

+0

在這裏看到:http://stackoverflow.com/questions/7306214/append-lines-to-a-file-using-a-streamwriter – 2014-10-10 15:07:41

+4

不明白爲什麼不使用nBook.TxtFileName +」的txt。 「 – 2014-10-10 15:08:02

+0

嗯,我已經把這個問題解釋爲問如何寫文件,而不是如何讓文件名在末尾有」.txt「。 @JBTGE,你有什麼問題嗎? – 2014-10-10 15:09:07

回答

-1

您必須聲明它在你的StreamWriter構造函數,你的情況:

OutputFile = new StreamWriter(nBook.TxtFileName + ".txt"); 
+0

@CaptainFindus它似乎沒有格式是正確的,我建議:'OutputFile = new StreamWriter(nBook.TxtFileName +「.txt」);' – Wizard 2014-10-10 15:13:32

+0

剛按'。'沒有看到,-2的答案...大聲笑 – CapitanFindus 2014-10-10 15:16:13

2

工作的呢?但願如此。

OutputFile = new StreamWriter(string.format("{0}.txt", nBook.TxtFilename)); 
+0

是的,我也發現,以下工作: OutputFile = new StreamWriter(nBook.TxtFileName +「。txt」); – JBTGE 2014-10-10 15:20:23