[英]How can I edit a text file using C#?
假設我有一個包含以下內容的文本文件:
你好!
你好嗎?
我想通過一個簡單的應用程序調用該文件,該應用程序生成一個包含以下內容的輸出文件:
buildLetter.Append("Hello!").AppendLine();
buildLetter.Append("How are you?").AppendLine();
如您所見,每一行都應放在“”之間。
任何幫助將不勝感激。
void ConvertFile(string inPath, string outPath)
{
using (var reader = new StreamReader(inPath))
using (var writer = new StreamWriter (outPath))
{
string line = reader.ReadLine();
while (line != null)
{
writer.WriteLine("buildLetter.Append(\"{0}\").AppendLine();",line.Trim());
line = reader.ReadLine ();
}
}
}
您應該自己添加一些I / O異常處理。
如果要追加""
在每一行,你可以嘗試結合ReadAllLines和WriteAllLines方法:
File.WriteAllLines(
"output.txt",
File
.ReadAllLines("input.txt")
.Select(line => string.Format("\"{0}\"", line))
.ToArray()
);
請注意,這會將整個文件內容加載到內存中,因此對於非常大的文件不能很好地工作。 在這種情況下,流閱讀器和編寫器更適應。
對於一個小文本文件,這對我有用。
private void EditFile(string path, string oldText, string newText)
{
string content = File.ReadAllText(path);
content = contenido.Replace(oldText, newText);
File.WriteAllText(path, content);
}
使用System.IO中的StreamReader類
請參閱此鏈接以獲取示例代碼
您可能需要做的就是更改線路
Console.WriteLine(sr.ReadLine());
至
Console.WriteLine(""""" + sr.ReadLine() + """""); // handwritten code - not tested :-)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.