Skip to main content
 首页 » 编程设计

c#之使用 Streamreader 的输入不会在 StreamWriter 中给出相同的输出

2024年08月06日38haluo1

我正在使用 StreamReader 读取一个文件,然后使用 StreamWriter 将准确的行写入另一个文件。然而,我遇到的问题是,在生成的文件中,任何出现的字符“¦”都会转换为“?”。

这是初始化我的流的代码:

using (var readFile = new FileStream(path, FileMode.Open, FileAccess.Read)) 
{ 
    using (var writeFile = new FileStream(@"Modified\" +   Path.GetFileName(path), FileMode.Create, FileAccess.Write)) 
    { 
        using (var sr = new StreamReader(readFile, new ASCIIEncoding())) 
        { 
            using (var sw = new StreamWriter(writeFile, new ASCIIEncoding())) 
            { 
                //Read line and write it to the writer 
            } 
        } 
    } 
} 

这可能是流的问题,还是更有可能是原始文件的问题?原始文件本身在多个文本编辑器中显示得很好,所以看起来是正确的。

请您参考如下方法:

¦ 不是有效的 ASCII 字符,所以我假设原始文件不是 ASCII 编码的。将编码类型更改为 UTF 可以解决问题,但很难知道这是否符合您的要求。

using (var sr = new StreamReader(readFile, new UTF8Encoding())) 
{ 
    using (var sw = new StreamWriter(writeFile, new UTF8Encoding())) 

参见 http://www.asciitable.com/ fpr 有效的 ascii 字符列表。