从文本文件c#中剪切和粘贴文本行

本文关键字:文本 文件 | 更新日期: 2023-09-27 18:12:53

大家好,初学者在这里寻找一些关于我用c#编写的程序的建议。我需要能够打开一个文本文档,读取文本的第一行(即不是空白),将这行文本保存到另一个文本文档,最后用空行覆盖读取行。

这就是我到目前为止所拥有的,一切都很好,直到最后一部分,我需要写一个空白行到原始文本文档,我只是得到一个完整的空白文档。就像我上面提到的,我是c#的新手,所以我确信有一个简单的解决方案,但我不能弄清楚,任何帮助感谢:

try
            {
                StreamReader sr = new StreamReader(@"C:'Users'Stephen'Desktop'Sample.txt");
                line = sr.ReadLine();
                while (line == "")
                {
                    line = sr.ReadLine();
                }
                sr.Close();
                string path = (@"C:'Users'Stephen'Desktop'new.txt");
                if (!File.Exists(path))
                {
                    File.Create(path).Dispose();
                    TextWriter tw = new StreamWriter(path);
                    tw.WriteLine(line);
                    tw.Close();
                }
                else if (File.Exists(path))
                {
                    TextWriter tw = new StreamWriter(path, true);
                    tw.WriteLine(line);
                    tw.Close();
                }
                StreamWriter sw = new StreamWriter(@"C:'Users'Stephen'Desktop'Sample.txt");
                int cnt1 = 0;
                while (cnt1 < 1)
                {
                    sw.WriteLine("");
                    cnt1 = 1;
                }
                sw.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: " + e.Message);
            }
            finally
            {
                Console.WriteLine("Executing finally block.");
            }
        else
            Console.WriteLine("Program Not Installed");
        Console.ReadLine();

从文本文件c#中剪切和粘贴文本行

不幸的是,您必须经历重写文件的艰苦过程。在大多数情况下,您可以将其加载到内存中,然后执行如下操作:

string contents = File.ReadAllText(oldFile);
contents = contents.Replace("bad line!", "good line!");
File.WriteAllText(newFile, contents);

请记住,您必须在这里处理换行的想法,因为string.Replace并不天生只关注整行。但这当然是可行的。您也可以在这种方法中使用正则表达式。您还可以使用File.ReadAllLines(string)将每一行读入IEnumerable<string>,并在将它们写回新文件时对每一行进行测试。这取决于你到底想做什么,以及你想做得有多精确。

using (var writer = new StreamWriter(newFile))
{
    foreach (var line in File.ReadAllLines(oldFile))
    {
        if (shouldInsert(line))
            writer.WriteLine(line);
    }
}

当然,这取决于谓词shouldInsert,但是您可以根据需要修改它。但IEnumerable<T>的性质应该使其相对较少依赖资源。您还可以使用StreamReader来获得较低级别的支持。

using (var writer = new StreamWriter(newFile))
using (var reader = new StreamReader(oldFile))
{
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        if (shouldInsert(line))
            writer.WriteLine(line);
    }
}
当然,回想一下,这可能会在文件末尾留下额外的空行。我太累了,不能肯定地说我应该能做到,但我很确定情况就是这样。留意一下,如果这真的很重要的话。当然,它通常不会。

总而言之,最好的方法是在不浪费内存的情况下,通过编写一个函数来读取FileStream并将适当的字节写入新文件,从而获得一点乐趣。当然,这是最复杂和可能过度杀戮的方式,但这将是一项有趣的事业。

参见:使用StreamWriter向文件追加行

true添加到StreamWriter构造函数中,设置为"追加"模式。请注意,这会在文档的底部添加一行,因此您可能需要稍微调整一下才能在顶部插入或覆盖它。

参见:在c#中编辑文本文件的特定行

显然,插入或覆盖单行并不是那么容易,通常的方法是复制所有行,同时替换您想要的行,并将每一行写回文件。