问题描述
我使用visual c#构建了一个Windows应用程序表单,它读取现有文件(读取所有行,并仅打印包含inactive字的行)并写入现有文件(newoverride.txt)。
但是输出文件上没有打印任何内容。
你可以帮忙解决一下吗?
我尝试了什么:
I have build a windows application form with visual c#, which reads an existing file (reads all lines, and prints only lines which include "inactive"-word on it) and writes to an existing file (newoverride.txt).
But is not printing anything on the output file.
Can u help how can I fix?
What I have tried:
string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
StreamReader file = new StreamReader(path);
List<string> Inactive = new List<string>();
while (file.EndOfStream != true)
{
string s = file.ReadLine();
Match m = Regex.Match(s, "(?<=Inactive)(.)+");
if (m.Success)
{
Inactive.Add(m.ToString());
}
{
s = String.Empty;
}
string path2 = path + "@\newoverride.txt";
using (StreamWriter outputFile = new StreamWriter(path2))
label2.Text = "File is converted ";
}
}
}
}
推荐答案
没有在输出文件上打印任何内容。
not printing anything on the output file.
嗯......它不会。
那是因为你不喜欢告诉它。
你打开一个输出流:
Well...it won't.
And that's because you don't tell it to.
You open an output stream:
using (StreamWriter outputFile = new StreamWriter(path2))
label2.Text = "File is converted ";
但是你没有写任何东西。
即使你这样做了,输出流也会在你的循环中打开 - 所以每次你打开它时,都会抛弃任何以前的内容。
打开循环外的输出流,并在其中写入循环,或写整个非活动集合,其中包含完成循环后需要编写的行。
和BTW:这不会让你想要你想要的:
But you don't write anything into it.
Even if you did, the output stream is opened inside your loop - so every time you open it, you throw away any previous content.
Open the output stream outside the loop, and write to it inside the loop, or write the whole Inactive collection is that contains the lines you need to write once teh loopis complete.
And BTW: this doesn't give you want you wanted:
string path2 = path + "@\newoverride.txt";
它给你一个以atsign和换行符开头的字符串......可能你的意思是:
It gives you a string which starts with an atsign and a newline... Probably you meant this:
string path2 = path + @"\newoverride.txt";
但即便如此,它可能会失败 - 写入启动驱动器的根文件夹是受限制的,可能会失败。
But even then, the chances are it will fail - writing to the root folder of your boot drive is restricted, and will likely fail.
这篇关于如何通过使用C#读取现有文件来写入现有文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!