C#:前置到文件的开头 [英] C#: Prepending to beginning of a file

查看:21
本文介绍了C#:前置到文件的开头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 C# 在文件开头添加文本的最佳方法是什么?

What is the best way to add text to the beginning of a file using C#?

我找不到一种直接的方法来做到这一点,但想出了几个变通办法.

I couldn't find a straightforward way to do this, but came up with a couple work-arounds.

  1. 打开新文件,写入我想添加的文本,将旧文件中的文本附加到新文件的末尾.

  1. Open up new file, write the text that I wanted to add, append the text from the old file to the end of the new file.

由于我要添加的文本应该少于200个字符,所以我想我可以在文件的开头添加空格字符,然后用我要添加的文本覆盖空格.

Since the text I want to add should be less than 200 characters, I was thinking that I could add white space characters to the beginning of the file, and then overwrite the white space with the text I wanted to add.

有没有其他人遇到过这个问题,如果有,你是怎么做的?

Has anyone else come across this problem, and if so, what did you do?

推荐答案

添加到文件的开头(前置而不是附加)通常不是受支持的操作.您的 #1 选项很好.如果你不能写一个临时文件,你可以把整个文件拉到内存中,将你的数据预存到字节数组中,然后将其覆盖掉(这只有在你的文件很小而且你不必这样做的情况下才真正可行)一次在内存中有一堆,因为在没有副本的情况下预先准备数组也不一定容易).

Adding to the beginning of a file (prepending as opposed to appending) is generally not a supported operation. Your #1 options is fine. If you can't write a temp file, you can pull the entire file into memory, preprend your data to the byte array and then overwrite it back out (this is only really feasible if your files are small and you don't have to have a bunch in memory at once because prepending the array is not necessarily easy without a copy either).

这篇关于C#:前置到文件的开头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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