在C#中添加文本到文件的开头和结尾 [英] Adding text to beginning and end of file in C#
问题描述
$ b $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ b //打开文件
StreamReader sr = new StreamReader(file.FullName);
//添加开始和结束标记
string text =< root> + sr.ReadToEnd()+< root>;
sr.Close();
//现在打开相同的文件写入
StreamWriter sw = new StreamWriter(file.FullName,false);
sw.Write(text);
sw.Close();
$ b $ p
$ b $ p $
$ div class =为了避免将整个文件保存在内存中,请重命名原始文件,然后使用
StreamReader
打开它。然后用 StreamWriter
打开原来的文件名来创建一个新的文件。 编写< ; root>
前缀到文件中,然后将数据以大块的形式从读写器复制到写入器。当你传输完所有的数据后,写下关闭的< / root>
(注意,如果你希望它是XML的话,可以使用正斜杠)。然后关闭这两个文件并删除重命名的原始文件。
char [] buffer = new char [10000];
字符串renamedFile = file.FullName +.orig;
File.Move(file.FullName,renamedFile); (StreamReader sr = new StreamReader(renamedFile))
using(StreamWriter sw = new StreamWriter(file.FullName,false))
{
sw.Write ( <根> 中);
int read; ((read = sr.Read(buffer,0,buffer.Length))> 0)
sw.Write(buffer,0,read);
sw.Write(< / root>);
}
File.Delete(renamedFile);
I have a process which picks up a series of "xml" files. The reason I put xml in quotes is that that the text in the file does not have a root element which makes in invalid xml. In my processing, I want to correct this and open up each file add a root node to the beginning and end of each file, and then close it up. Here is what I had in mind, but this involves opening the file, reading the entire file, tagging on the nodes, and then writing the entire file out. These files may be more than 20 MB in size.
foreach (FileInfo file in files)
{
//open the file
StreamReader sr = new StreamReader(file.FullName);
// add the opening and closing tags
string text = "<root>" + sr.ReadToEnd() + "<root>";
sr.Close();
// now open the same file for writing
StreamWriter sw = new StreamWriter(file.FullName, false);
sw.Write(text);
sw.Close();
}
Any recommendations?
To avoid holding the whole file in memory, rename the original file, then open it with StreamReader
. Then open the original filename with StreamWriter
to create a new file.
Write the <root>
prefix to the file, then copy data in large-ish chunks from the reader to the writer. When you've transferred all the data, write the closing </root>
(note the forward slash if you want it to be XML). Then close both files and delete the renamed original.
char[] buffer = new char[10000];
string renamedFile = file.FullName + ".orig";
File.Move(file.FullName, renamedFile);
using (StreamReader sr = new StreamReader(renamedFile))
using (StreamWriter sw = new StreamWriter(file.FullName, false))
{
sw.Write("<root>");
int read;
while ((read = sr.Read(buffer, 0, buffer.Length)) > 0)
sw.Write(buffer, 0, read);
sw.Write("</root>");
}
File.Delete(renamedFile);
这篇关于在C#中添加文本到文件的开头和结尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!