SoFunction
Updated on 2025-03-06

C# Use Filestream to modify the specified location data of large files

Preface

General process for reading and writing files in C#

FileStream fs = new FileStream(filePath, , );
//readStreamReader sr=new StreamReader(fs);
string line=();

//WriteStreamWriter s = new StreamWriter(fs);
("xxx");

As for modifying content, most of the online contents are first read all the contents of the file into memory, and then modify the contents and write them to the file. This will have no problem with small files, but it is not feasible for large files;

Operation steps

  • We first write a function to read a line of data
   /// <summary>
   /// Start reading the content of the line change at the current location of the file stream. Return to the length of the line change   /// </summary>  
   private long readRow(FileStream fs20O)
   {
            long len = 0;

            byte[] b = new byte[1];

            bool exit = false;

            while (true)
            {
                if ((b, 0, 1) == -1) break;

                len++;
                string str = Encoding.(b);
                (str);
                if ("\n".Equals(str))
                {
                    return len;
                }
            }

            return len;
     }

Then someone will ask, why don’t I read a line without ()?

Since you need to modify the content of the current line next, when you read the current line and determine that you need to modify it, you need to move the position of the stream to the beginning of the line, and get the read length based on the above function. Use the code

 (-len, );

If you use len=() and move the pointer, you will find that the position of the stream will be later than offset len. I don’t know if readLine will pre-read, which leads to you that it only reads one line. In fact, it moves the stream pointer to the last few lines and caches the data. When doing offsets, the result is wrong. This is why you need to use the above method to read it;

  • OK, next iterate through the file contents
long len=0;
while((len=readRow(fs)!=-1)
{
    //......
    //Modify content    //Move the file pointer to the beginning of the line    if(true)
    {
        (-len, );
        byte[] readWriteByte = Encoding.("Test");
        //The original content will be replaced directly        (readWriteByte, 0, );
        //***Continue to read down until the end of the line. Move the pointer to the beginning of the next line.        readRow(fs);

        //After modifying, it will jump out of the loop and save the file        break;
    }
}

This is the article about C# using Filestream to modify the specified location data of large files. For more related C# Filestream content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!