2017-02-11 120 views
1

我正在使用C#創建一個txt文件並寫入多行。問題在於該行在頂部附加,而不是結尾。如何在C#中使用File.Append添加文件末尾的行#

有關如何實現此目的的任何信息。 這是下面的代碼

private static void WriteReleaseSql(string sqlStatement) 
    { 
     string ReleaseoutputFilePath = ConfigurationManager.AppSettings["ReleaseOutputFilePath"]; 

     using (FileStream fs = new FileStream(ReleaseoutputFilePath, FileMode.Append, FileAccess.Write)) 
     using (StreamWriter sw = new StreamWriter(fs)) 
     { 
      sw.WriteLine(sqlStatement); 
     } 
    } 
+2

對我來說這段代碼按預期工作。該行將被添加到文件的末尾。 – Steve

回答

1

您可以使用StreamWriter沒有FileStream(用戶實例),它爲我

private static void WriteReleaseSql(string sqlStatement) 
{ 
    string ReleaseoutputFilePath = ConfigurationManager.AppSettings["ReleaseOutputFilePath"]; 

    using (StreamWriter sw = new StreamWriter(ReleaseoutputFilePath,True)) 
    { 
     sw.WriteLine(sqlStatement); 
    } 
} 

注正常工作:你的代碼工作正常

+1

只有沒有「可見」流。還有一個。 –

+0

我同意這一點 – Hadi

-1

使用Environment.NewLine到添加一個新行。

1

當我檢查MDSN網站的FileMode時,這是我得到的定義。

打開文件,如果它存在並尋求到文件的末尾,或者 創建一個新文件。這需要FileIOPermissionAccess。附加 權限。 FileMode.Append只能與 FileAccess.Write一起使用。在 文件結束之前嘗試尋找位置會引發IOException異常,並且任何嘗試讀取的文件都會失敗 並引發NotSupportedException異常。

就文檔而言,它應該在最後附加一些東西。請再次檢查輸出。

雖然我真的想知道如何在頂部添加東西。

相關問題