如何在 C# 中读取和编辑 .txt 文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1368539/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I read and edit a .txt file in C#?
提问by George Powell
For example, I have a txt file that reads:
例如,我有一个 txt 文件,内容如下:
12 345 45
2342 234 45 2 2 45345
234 546 34 3 45 65 765
12 23 434 34 56 76 5
I want to insert a comma between all the numbers, add a left brace to the begining of each line and a right brace to the end of each line. So after the editing it should read:
我想在所有数字之间插入一个逗号,在每行的开头添加一个左括号,在每行的末尾添加一个右括号。所以在编辑后它应该是:
{12, 345, 45}
{2342, 234, 45, 2, 2, 45345}
{234, 546, 34, 3, 45, 65, 765}
{12, 23, 434, 34, 56, 76, 5}
How do I do it?
我该怎么做?
采纳答案by aanund
Added some LINQ for fun and profit (room for optimization ;) ):
添加了一些 LINQ 以获得乐趣和利润(优化空间;)):
System.IO.File.WriteAllLines(
"outfilename.txt",
System.IO.File.ReadAllLines("infilename.txt").Select(line =>
"{" +
string.Join(", ",
line.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries)
) + "}"
).ToArray()
);
回答by Donut
You'll need to use the FileStreamclass to open the file, the StreamReaderclass to read from the file, and the StreamWriterclass to write back to the file.
您需要使用FileStream类打开文件,使用StreamReader类从文件中读取,使用StreamWriter类写回文件。
You can create a FileStreamlike this:
你可以创建一个FileStream这样的:
FileStream file = new FileStream("FileName", FileMode.Open, FileAccess.ReadWrite);
Then wrap the FileStreamin a StreamReader:
然后将其包裹FileStream在 a 中StreamReader:
StreamReader reader = new StreamReader(file);
Then, read in each line and do your string processing (adding commas and brackets):
然后,读入每一行并进行字符串处理(添加逗号和括号):
while(reader.EndOfFile)
{
string currentLine = reader.ReadLine();
// do your string processing here and save the result somewhere
}
Lastly, wrap the FileStreamin a StreamWriterand write your modified strings back to the file:
最后,将 包裹FileStream在 a 中StreamWriter并将修改后的字符串写回文件:
StreamWriter writer = new StreamWriter(file);
// Write your content here
writer.Write("my content");
Don't forget to close your streams after working with them.
不要忘记在使用它们后关闭你的流。
reader.Close();
writer.Close();
file.Close();
回答by waqasahmed
Read each line.
阅读每一行。
Add a bracket before the string and after
在字符串之前和之后添加一个括号
Then replace space " " by ", " (comma and space)
然后用“,”替换空格“”(逗号和空格)
回答by cw22
you should work on the logic first instead of directly asking people to provide that for you. as for reading/writing a file, here you go:
您应该首先研究逻辑,而不是直接要求人们为您提供逻辑。至于读/写文件,你去吧:
//write
FileStream fs = new FileStream("file_name", FileMode.Create);
StreamWriter w = new StreamWriter(fs, Encoding.UTF8);
w.WriteLine("text_to_write");
w.Flush();
w.Close();
fs.Close();
//read
fs = new FileStream("file_name", FileMode.Open);
StreamReader r = new StreamReader(fs, Encoding.UTF8);
Console.WriteLine(r.ReadLine());
r.Close();
fs.Close();
回答by 3Dave
- Load the whole file
- use string.split('\n') to divide the contents into lines
- use string.replace(' ',',') to insert commas.
- Save the file.
- 加载整个文件
- 使用 string.split('\n') 将内容分成几行
- 使用 string.replace(' ',',') 插入逗号。
- 保存文件。
Or, as waqasahmed said, just do it one at a line.
或者,正如 waqasahmed 所说,只做一个线。
See also: http://www.csharphelp.com/archives/archive24.html
另见:http: //www.csharphelp.com/archives/archive24.html
Also, this sounds suspiciously like a homework problem. Maybe we should have a "homework" tag?
此外,这听起来像一个家庭作业问题。也许我们应该有一个“家庭作业”标签?
回答by Mark Redman
Something like this: (NOT TESTED)
像这样的东西:(未测试)
string filename = @"c:\yourfilename.txt";
StringBuilder result = new StringBuilder();
if (System.IO.File.Exists(filename))
{
using (StreamReader streamReader = new StreamReader(filename))
{
String line;
while ((line = streamReader.ReadLine()) != null)
{
string newLine = String.Concat("{", line, "}", Environment.NewLine);
newLine = newLine.Replace(" ", ", ");
result.Append(newLine);
}
}
}
using (FileStream fileStream = new FileStream(filename , fileMode, fileAccess))
{
StreamWriter streamWriter = new StreamWriter(fileStream);
streamWriter.Write(result);
streamWriter.Close();
fileStream.Close();
}
回答by jb.
edit to add how to modify sLine. (not tested, but I'm pretty sure it'll work just fine)
编辑以添加如何修改 sLine。(未经测试,但我很确定它会正常工作)
StreamReader sr = new StreamReader("path/to/file.txt");
StreamWriter sw = new StreamWriter("path/to/outfile.txt");
string sLine = sr.ReadLine();
for (; sLine != null; sLine = sr.ReadLine() )
{
sLine = "{" + sLine.Replace(" ", ", ") + "}";
sw.WriteLine(sLine);
}
回答by George Powell
In the end I used a second file rather than editing the first:
最后我使用了第二个文件而不是编辑第一个文件:
TextReader reader = new StreamReader("triangle.txt");
TextWriter writer = new StreamWriter("triangle2.txt");
for (; ; )
{
string s = reader.ReadLine();
if (s == null)
break;
s = s.Replace(" ", ", ");
s = "{" + s + "},";
writer.WriteLine(s);
}
回答by Mehmet Aras
string [] lines = File.ReadAllLines("input.txt");
var processed = lines.Select(line => string.Format("{{{0}}}", line.Replace(" ", ", ")));
File.WriteAllLines("output.txt",processed.ToArray());

