简体   繁体   English

如何使用C#编辑文本文件?

[英]How can I edit a text file using C#?

Lets say i have a text file with following content: 假设我有一个包含以下内容的文本文件:

Hello! 你好!
How are you? 你好吗?

I want to call the file via a simple application that produces an output file with the following contents: 我想通过一个简单的应用程序调用该文件,该应用程序生成一个包含以下内容的输出文件:

buildLetter.Append("Hello!").AppendLine(); 
buildLetter.Append("How are you?").AppendLine();

As you see, every line should be put between " ". 如您所见,每一行都应放在“”之间。

Any help will be appreciated. 任何帮助将不胜感激。

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 ();    
        }
    }
}

You should add some I/O exception handling on your own. 您应该自己添加一些I / O异常处理。

If you want to append "" to each line you could try combining the ReadAllLines and WriteAllLines methods: 如果要追加""在每一行,你可以尝试结合ReadAllLinesWriteAllLines方法:

File.WriteAllLines(
    "output.txt",
    File
        .ReadAllLines("input.txt")
        .Select(line => string.Format("\"{0}\"", line))
        .ToArray()
);

Notice that this loads the whole file contents into memory so it wouldn't work well with very large files. 请注意,这会将整个文件内容加载到内存中,因此对于非常大的文件不能很好地工作。 In this case stream readers and writers are more adapted. 在这种情况下,流阅读器和编写器更适应。

For a small text files this works for me. 对于一个小文本文件,这对我有用。

private void EditFile(string path, string oldText, string newText)
        {
            string content = File.ReadAllText(path);
            content = contenido.Replace(oldText, newText);
            File.WriteAllText(path, content);
        }

Use the StreamReader class from System.IO 使用System.IO中的StreamReader类

Refer this link for sample code 请参阅此链接以获取示例代码

All you probably need to do is change the line 您可能需要做的就是更改线路

Console.WriteLine(sr.ReadLine());

to

Console.WriteLine(""""" + sr.ReadLine() + """"");  // handwritten code - not tested :-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM