删除文件的最后10个字符 [英] remove last 10 characters of a file

查看:82
本文介绍了删除文件的最后10个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要删除文件的最后10个字符.假设字符串"hello i am a c# learner"是文件中的数据.

I want to remove the last 10 characters of a file. Say a string "hello i am a c# learner" is the data inside the file .

我只希望该文件为"hello i am a ".文件的最后10个字符(字符串"c# learner")应在文件内部消除.

I just want that file to be "hello i am a ". The last 10 characters of the file that is the string "c# learner" should be eliminated inside the file.

解决方案:

  1. 将整个文件读取为一个字符串,然后删除最后10个字符并写回该字符串(但是,当文件大小太大时,例如大约200 MB的文件,这种方法将失败,这甚至是不必要的方式来读取整个文件文件,因为我们只需要最后10个字符.所以我无法尝试这种方法)

  1. read the entire file into a string and remove those last 10 characters and write back the string (but this approach fails when the file size is too big say some 200 MB file and it is even unnecessary way to read entire file when we need only last 10 characters. So I could not try this approach)

我想以写模式打开文件并设置光标位置类似file.seek(-10,SeekOrigin.End)并写空字节file.writebye((byte)((char)' '));

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

但是似乎没有向文件中写入任何内容.

But it does not seem to write anything to the file.

有人能告诉我一种更好的方法,而不是将整个文件读成字符串.

Could anyone tell me the better way to approach it instead of reading entire file into a string.

注意,我正在使用c#来实现

NOTE I am using c# to do this

推荐答案

获取文件大小(使用FileInfo),打开文件(使用FileStream)并将其长度设置为所需大小.

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

这篇关于删除文件的最后10个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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