在.NET基于字符的文件流 [英] character based file stream in .NET

查看:130
本文介绍了在.NET基于字符的文件流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要修改未知编码的文本文件中,我需要一个predefined字符串(如#markx#)第一次出现后插入一些文本。有没有在.NET中的一类,让我随机访问文件的的内容,但基于字符(而不是字节)。由于Stream.Seek方法的工作在字节基础上,我不仅需要知道编码,但也知道如果有一些特殊的控制字节(如在大学code文件开头的第一个字节)。我很想有abstact一切都抛开,让我说类:寻求25个字符,并添加一些字符串有的只是作为一个文本编辑会做到这一点。

I need to modify a textfile of unknown encoding in that I need to insert some text after the first occurence of a predefined string (e.g. "#markx#"). Is there a class in .NET that allows me to randomly access the content of a file but based on characters (as opposed to bytes). Since the Stream.Seek Methods work on byte basis I would not only need to know the encoding but also know if there are some special control bytes (such as the first bytes at the beginning of unicode file). I would love to have a class that abstact all this away and allows me to "say": seek to 25th character and add some string there just as a texteditor would do it.

推荐答案

您可以使用的StreamReader 要经过一个字符的时间 - 没有一个寻找方法,但你仍然可以阅读逐字节,因此有效地实现自己所追求的。

You can use a StreamReader to go through one character at a time - there isn't a Seek method, but you can still read byte-by-byte and so effectively implement your own seek.

对于编码 - 你必须要使用的StreamReader 确定的编码。

With regard to encodings - you will need to have identified the encoding in order to use the StreamReader.

不过,的StreamReader 本身可以帮助,如果您的构造函数重载,允许你提供标志之一,创建 detectEncodingFromByteOrderMarks 为真(或者您可以使用 Encoding.Get preamble ,并期待在字节preamble自己)。

However, the StreamReader itself can help if you create it with one of the constructor overloads that allows you to supply the flag detectEncodingFromByteOrderMarks as true (or you can use Encoding.GetPreamble and look at the byte preamble yourself).

这两种方法只会帮助自动检测UTF编码的基础,虽然 - 所以任何ANSI编码与指定的codePAGE将可能无法正确​​解析

Both these methods will only help auto-detect UTF based encodings though - so any ANSI encodings with a specified codepage will probably not be parsed correctly.

这篇关于在.NET基于字符的文件流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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