Delete last 10 characters of file

I want to delete the last 10 characters of a file. Let's say a line "hello i am a c# learner"is data inside a file.

I want this file to be "hello i am a ". The last 10 characters of the file, which is a string "c# learner", must be deleted inside the file.

Decision:

  • read the entire file in a line and delete these last 10 characters and write a line (but this approach does not work if the file size is too large, say about 200 MB of file, and you don’t even need to read the entire text of the file when we need only the last 10 characters Therefore, I could not try this approach)

  • I thought to open the file in write mode and set the cursor position something like this: file.seek(-10,SeekOrigin.End)and write empty bytesfile.writebye((byte)((char)' '));

But he does not write anything to the file.

Can someone tell me the best way to approach it instead of reading the entire file in a line.

NOTE I use C # for this

+2
source share
3 answers

Get the file size (using FileInfo), open the file (using FileStream) and set its length to the desired size.

+1
source

If the file path is in the text box:

FileStream fs = new FileStream(textBox1.Text, FileMode.Open, FileAccess.ReadWrite);
fs.SetLength(fs.Length - 10);
fs.Close();
+6
source

Perhaps you could try something like this?

yourString = yourString.Remove(yourString.Length -10);
+1
source

Source: https://habr.com/ru/post/1649739/


All Articles