![](/img/trans.png)
[英]Blocking a file while writing it using FileStream append mode in C#
[英]C# - Writing to file with filestream
這是使用 Filestream 的正確方法嗎? 如果是這樣,我可以在這個 function 中改進什么嗎? 它的主要計划是用於寫入包含 600 多行數據的 ftp 文件夾。
我關心的是 for 循環。
這是我第一次使用 C# 工作。 所以我可以使用建議。
private void button3_Click(object sender, EventArgs e)
{//FINISH BUTTON
if (string.IsNullOrEmpty(FilePathBox.Text) || string.IsNullOrEmpty(FileNameBox.Text))
{
MessageBox.Show("Please check folderpath or filename.",
"WARNING");
}
else
{
String vFullPath = FilePathBox.Text + "/" + FileNameBox.Text + ExtentionBox.Text;
MainProgressBar.Maximum = OutputBox.Items.Count;
using (FileStream fs = File.Create(vFullPath))
{
for (int i = 0; i < OutputBox.Items.Count; i++)
{
//String vInput = OutputBox.Items[i].ToString() + "\n";
//File.AppendAllText(vFullPath, vInput);
String vInput = OutputBox.Items[i].ToString() + "\n";
byte[] vData = new UTF8Encoding(true).GetBytes(vInput);
fs.Write(vData, 0, vData.Length);
MainProgressBar.Value = i;
}
}
MainProgressBar.Value = MainProgressBar.Maximum;
MessageBox.Show("Finished Writing to file.",
"Completed");
}
}
一種更典型的方法是將 stream 包裝在 StreamWriter 中,它具有字符串的寫入方法,無需將所有內容轉換為字節。 您可以在構造函數中使用 select 編碼。 還有一個用於寫入二進制數據的 BinaryWriter。
循環寫入數據不是問題。 您也許可以使用String.Join
在 memory 中創建一個完整的字符串,然后使用File.WriteAllLines
,但我不希望獲得太多。
我報告進度的首選方法是使用Task.Run
在后台線程上運行工作,在共享 object 中設置一個描述進度的屬性,並在 UI 線程上創建一個計時器來輪詢所述屬性並更新進度條。 這有助於確保 UI 具有響應性。
我還會考慮使用某種序列化庫,例如json.net 。 這極大地簡化了將 object 轉換為文件並再次返回的過程。 但它與日志記錄之類的事情不太相關。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.