如何使用 StreamWriter 在 c# 中编辑文本文件? [英] How to edit a text file in c# with StreamWriter?

查看:53
本文介绍了如何使用 StreamWriter 在 c# 中编辑文本文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a method to edit a word from a text file file and display it on the command prompt. Now I an trying to make a method to edit a word from a text file and write it to a new file. I would also like to mention that I cannot use the File or Regex class since I am not allowed to use it for my assignment. Here is my code for the 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 编写的代码:

and here is my code so far for the 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 中进行这些更改?谢谢

what can I add to make the StreamWriter open a file, edit a word and write it to a new file or possibly use the StreamReader method to make these changes in StreamWriter? Thank you

推荐答案

这里...

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

这篇关于如何使用 StreamWriter 在 c# 中编辑文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆