3

我有一种方法可以从文本文件文件中编辑一个单词并将其显示在命令提示符下。现在我试图制作一种方法来编辑文本文件中的单词并将其写入新文件。我还想提一下,我不能使用 File 或 Regex 类,因为我不允许将它用于我的作业。这是我的 StreamReader 代码:

public void EditorialControl(string fileName, string word, string replacement)
{            
    List<string> list = new List<string>();
    using (StreamReader reader = new StreamReader(directory + fileName))
    {
        string line;
        while ((line = reader.ReadLine()) != null)
        {                    
            line = line.Replace(word, replacement);
            list.Add(line);
            Console.WriteLine(line);
        }
        reader.Close();
    }      
}

到目前为止,这是我的 StreamWriter 代码:

public void EditorialResponse(string fileName, string word, string replacement, string saveFileName)
{
    using (StreamWriter writer = new StreamWriter(directory + saveFileName, true))
    {
        {
            string input = directory + fileName;
            string line = input.Replace(word, replacement);
            writer.Write(line);                     
        }
        writer.Close();
    }
}

我可以添加什么来使 StreamWriter 打开文件、编辑单词并将其写入新文件,或者可能使用 StreamReader 方法在 StreamWriter 中进行这些更改?谢谢

4

3 回答 3

6

这里...

public void EditorialResponse(string fileName, string word, string replacement, string saveFileName)
{
    StreamReader reader = new StreamReader(directory + fileName);
    string input = reader.ReadToEnd();

    using (StreamWriter writer = new StreamWriter(directory + saveFileName, true))
    {
        {
            string output = input.Replace(word, replacement);
            writer.Write(output);                     
        }
        writer.Close();
    }
}
于 2013-09-17T15:56:01.120 回答
4
public IList<string> GetEditedContent(string fileName, string word, string replacement)
{            
    List<string> list = new List<string>();
    using (StreamReader reader = new StreamReader(directory + fileName))
    {
        string line;
        while ((line = reader.ReadLine()) != null)
        {                    
            line = line.Replace(word, replacement);
            list.Add(line);
            Console.WriteLine(line);
        }
        reader.Close();
    }      
    return list;
}

    // Example how write list to a file. 
 using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\Public\TestFolder\WriteLines2.txt"))
    {
        foreach (string listItem in list)
        {
            file.WriteLine(listItem);
           
        }
    }

C# 编程指南中有关StreamWriter的示例

如何:写入文本文件(C# 编程指南)

于 2012-11-25T17:13:39.533 回答
0

您可以只使用这个简单的代码,它应该编辑您的“filename.txt”并附加新文本。

using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\TestFolder\filename.txt", true))
{
file.WriteLine("text to edit / append ...");
}
于 2017-06-20T08:05:05.220 回答