从文本文件C#中的文本剪切和粘贴线 [英] Cut and paste line of text from text file c#

查看:201
本文介绍了从文本文件C#中的文本剪切和粘贴线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好初学者在这里寻找一些建议与程序我在C#编写。我需要能够打开一个文本文档,文本阅读的第一行(即不为空),这行文字保存到另一个文本文档,最后覆盖有一个空行读线。



这是我到目前为止,一切工作正常,直到我需要写一个空行到原来的文本文档的最后一部分,我只是得到一个完全空白文件。就像我上面提到我是新的C#,所以我敢肯定有一个简单的解决了这个,但我无法弄清楚,任何帮助赞赏:

 
{
StreamReader的SR =新的StreamReader(@C:\Users\Stephen\Desktop\Sample.txt);

线= sr.ReadLine();

,而(行==)
{
线= sr.ReadLine();
}
sr.Close();
路径字符串=(@C:\Users\Stephen\Desktop\\\
ew.txt); (!File.Exists(路径))
如果
{
File.Create(路径).Dispose();
的TextWriter TW =新的StreamWriter(路径);
tw.WriteLine(线);
tw.Close();
}
,否则如果(File.Exists(路径))
{
的TextWriter TW =新的StreamWriter(路径,真实);
tw.WriteLine(线);
tw.Close();
}
的StreamWriter SW =新的StreamWriter(@C:\Users\Stephen\Desktop\Sample.txt);
INT CNT1 = 0;
,而(CNT1< 1)
{
sw.WriteLine();
CNT1 = 1;
}
sw.Close();

}
赶上(例外五)
{
Console.WriteLine(异常:+ e.Message);
}
终于
{
Console.WriteLine(执​​行finally块。);
}
,否则
Console.WriteLine(程序未安装);
到Console.ReadLine();


解决方案

不幸的是,你必须经过艰苦的过程重写该文件。在大多数情况下,你可以逃脱它加载到内存中,只是在做类似:

 字符串内容= File.ReadAllText( oldfile目录); 
含量= contents.Replace(坏行了!,好行了!);
File.WriteAllText(NEWFILE,内容);



请记住,你必须处理线的想法打破了这里,因为与string.replace 不天生只注意整行。但是,这肯定是可行的。你也可以使用正则表达式这种做法。您还可以使用 File.ReadAllLines(串)读每一行成的IEnumerable<串> 并测试每一个当你写他们回到新文件。这只是取决于正是你想要做什么,你想它是如何精确。

 使用(VAR作家=新StreamWriter的(NEWFILE))
{
的foreach(在File.ReadAllLines VAR线(oldfile目录))
{
如果(shouldInsert(线))
writer.WriteLine(线);
}
}

这当然取决于谓词 shouldInsert ,但可以修改,当你看到如此契合。但性质的IEnumerable< T> 应该是资源相对较轻。你也可以使用的StreamReader 为支持位较低级别。

 使用(VAR作家=新的StreamWriter(NEWFILE))使用(VAR读者=新的StreamReader(oldfile目录))
{
串线
;
,而((行= reader.ReadLine())!= NULL)
{
如果(shouldInsert(线))
writer.WriteLine(线);
}
}



回忆,当然,这可能留给你在该文件的末尾的额外,空行。我太累了,说跟我肯定应该是可以的,但我敢肯定是这样的话。只要保持留意的是,如果它真的很重要。当然,它通常不会。



这一切都表示,的的方式做到这一点是有一点乐趣和做到这一点不浪费内存,通过编写一个函数读取的FileStream 并写出相应的字节到新的文件。那是当然,最复杂,最有可能超杀的方式,但它会是一个有趣的任务。


Hi everyone beginner here looking for some advice with a program I'm writing in C#. I need to be able to open a text document, read the first line of text (that is not blank), save this line of text to another text document and finally overwrite the read line with an empty line.

This is what I have so far, everything works fine until the last part where I need to write a blank line to the original text document, I just get a full blank document. Like I mentioned above I'm new to C# so I'm sure there is an easy solution to this but I can't figure it out, any help appreciated:

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

解决方案

Unfortunately, you do have to go through the painstaking process of rewriting the file. In most cases, you could get away with loading it into memory and just doing something like:

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

Remember that you'll have to deal with the idea of line breaks here, since string.Replace doesn't innately pay attention only to whole lines. But that's certainly doable. You could also use a regex with that approach. You can also use File.ReadAllLines(string) to read each line into an IEnumerable<string> and test each one while you write them back to the new file. It just depends on what exactly you want to do and how precise you want to be about it.

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

That, of course, depends on the predicate shouldInsert, but you can modify that as you see so fit. But the nature of IEnumerable<T> should make that relatively light on resources. You could also use a StreamReader for a bit lower-level of support.

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

Recall, of course, that this could leave you with an extra, empty line at the end of the file. I'm too tired to say that with the certainty I should be able to, but I'm pretty sure that's the case. Just keep an eye out for that, if it really matters. Of course, it normally won't.

That all said, the best way to do it would be to have a bit of fun and do it without wasting the memory, by writing a function to read the FileStream in and write out the appropriate bytes to your new file. That's, of course, the most complicated and likely over-kill way, but it'd be a fun undertaking.

这篇关于从文本文件C#中的文本剪切和粘贴线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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