Search code examples
c#bufferfileinfo

Best way to prevent oversized Buffer File?


I want to delete a buffer File, filled by Values from a scale. So far this here is my code. But it deletes the whole file after a defined file size is reached.

if(File.ReadAllBytes("buffer1").Length >= 50)
                {
                    File.Delete("buffer1");
                }

I am sure there is a better way. Without deleting the whole file and keeping the las values in it. But how? Hope someone can help.


Solution

  • If you want to delete the first several values from a file, the best way to do it is to copy the rest of the values to a second file. Then you can overwrite the original file with the new file. Here is some example code.

        const string yourfile = "buffer1";
        const string tempfile = "buffer1edit.bin";
    
        System.IO.FileInfo fi = new System.IO.FileInfo(yourfile);
        if (fi.Length > 50)
        {
            using (System.IO.FileStream originalfile = System.IO.File.Open(yourfile, System.IO.FileMode.Open),
                newfile = System.IO.File.Open(tempfile, System.IO.FileMode.CreateNew))
            {
                originalfile.Seek(50, System.IO.SeekOrigin.Begin);
                originalfile.CopyTo(newfile);
            }
    
            System.IO.File.Delete(yourfile);
            System.IO.File.Move(tempfile, yourfile);
        }