修改FileStream [英] Modify FileStream

查看:72
本文介绍了修改FileStream的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究允许编辑非常大的文本文件(4Gb +)的课程.好吧,这听起来可能有些愚蠢,但是我不明白如何修改流中的文本.这是我的代码:

I'm working now on a class that will allow editing very big text files (4Gb+). Well it may sound a little stupid but I do not understand how I can modify text in a stream. Here is my code:

public long  Replace(String text1, String text2)
{
    long replaceCount = 0;
    currentFileStream = File.Open(CurrentFileName, FileMode.Open, FileAccess.ReadWrite, FileShare.None);

    using (BufferedStream bs = new BufferedStream(currentFileStream))
    using (StreamReader sr = new StreamReader(bs))  
    {
        string line;
        while ((line = sr.ReadLine()) != null)
        {
            if (line.Contains(text1))
            {
                line.Replace(text1, text2);

                // Here I should save changed line
                replaceCount++;
            }
        }
    }
    return replaceCount;
}

推荐答案

您没有在代码中的任何地方替换它.您应该保存所有文本,然后将其再次写入文件.喜欢,

You are not replacing it anywhere in your code. You should save all the text and then write it again to the file. Like,

  public long  Replace(String text1, String text2)
 {
  long replaceCount = 0;
   currentFileStream = File.Open(CurrentFileName, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
StringBuilder sb = new StringBuilder();
using (BufferedStream bs = new BufferedStream(currentFileStream))
using (StreamReader sr = new StreamReader(bs))  
{
    string line;
    while ((line = sr.ReadLine()) != null)
    {
        string textToAdd = line;
        if (line.Contains(text1))
        {
            textToAdd = line.Replace(text1, text2);

            // Here I should save changed line
            replaceCount++;
        }
        sb.Append(textToAdd);
    }
}
using (FileStream fileStream = new FileStream(filename , fileMode, fileAccess))
        {
            StreamWriter streamWriter = new StreamWriter(fileStream);
            streamWriter.Write(sb.ToString());
            streamWriter.Close();
            fileStream.Close();
        }
return replaceCount;

}

这篇关于修改FileStream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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