写入文本文件而不覆盖c#中的现有文件内容 [英] write to a text file without overwriting existing file content in c#

查看:245
本文介绍了写入文本文件而不覆盖c#中的现有文件内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我需要写一个现有的文本文件,而不会覆盖现有的内容.

假设文件sample.txt具有以下内容

sample.txt:

视觉C#
视觉基础
asp.net
网络服务

现在,我想在内容"webservices"下面写入相同的文件,如下所示

视觉C#
视觉基础
asp.net
网络服务
dotnet
wcf webservice

当我尝试使用streamwriter类进行写操作时,它会覆盖现有内容并使用新数据更新文件.示例代码如下所示.
谁能帮我注册一下.

Hi,

I need to write to an existing text file without overwriting the existing content.

Suppose the file sample.txt has following content

sample.txt:

visual c#
visual basic
asp.net
webservices

Now i want to write the same file below the content "webservices" as shown below

visual c#
visual basic
asp.net
webservices
dotnet
wcf webservice

when i tried to write using streamwriter class it overrides the existing content and updated the file with new data.Sample code is shown below.
Can anyone please help me reg this.

string path = Path.Combine(outputpath, outputfile);
         fileStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
         writer = new StreamWriter(fileStream, Encoding.UTF8);
         for (i = 0; i < dt.Columns.Count - 1; i++)
         {
             writer.Write(dt.Columns[i].ColumnName + ;);
         }
         writer.Write(dt.Columns[i].ColumnName + ;);
         writer.WriteLine(); /*For Data in the Rows*/

         foreach (DataRow row in dt.Rows)
         {
             object[] array = row.ItemArray;
             for (i = 0; i < array.Length - 1; i++)
             {
                 writer.Write(array[i].ToString() + ;);
             }
             writer.Write(array[i].ToString());
             writer.WriteLine();
         }
         writer.WriteLine("-------------------------------------------");
         writer.Flush();
         writer.Close();

推荐答案

这将附加到现有文件中.
This will be appended to the existing file.

// This text is always added, making the file longer over time
using (StreamWriter sw = File.AppendText(path))
{
    sw.WriteLine("This");
    sw.WriteLine("is Extra");
    sw.WriteLine("Text");
}



检查以下示例以获取完整示例:

http://msdn.microsoft.com/en-us/library/system. io.file.appendtext.aspx [ ^ ]



Check the following for complete example:

http://msdn.microsoft.com/en-us/library/system.io.file.appendtext.aspx[^]


听起来像您需要附加文本的声音
参见此处 [此处 [
Sounds like you need to append text
see here[^]

and here[^]


检查此博客
在没有临时文件或内存缓冲区的情况下,将文本插入C#中的现有文件中 [
check this blog
Insert Text into Existing Files in C#, Without Temp Files or Memory Buffers[^]
--NDK


这篇关于写入文本文件而不覆盖c#中的现有文件内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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