错误的编码,输出文件给出 而不是普通的char

时间:2013-05-28 22:23:57

标签: c# unicode encoding

我想创建一个程序,在文件中搜索所需的字符(字母čćž),用c z s等替换它们并保存文件。然而,在我的尝试中,我得到一些愚蠢的迹象,这意味着它错误地打开了文件。当我尝试添加encoding.unicode时,它会给我错误(如下所示)。还有一个问题,如何通过在.exe文件中拖动文件来创建一个打开文件的程序。

  

错误3最佳重载方法匹配   'System.IO.File.Open(string,System.IO.FileMode,   System.IO.FileAccess)'有一些无效   参数C:\ Users \ Vulisha \ AppData \ Local \ Temporary   Projects \ ConsoleApplication1 \ Program.cs 14 59 ConsoleApplication1

     

错误4参数'3':无法从'System.Text.Encoding'转换为   'System.IO.FileAccess'C:\ Users \ Vulisha \ AppData \ Local \ Temporary   Projects \ ConsoleApplication1 \ Program.cs 14 122 ConsoleApplication1

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;


namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            using (StreamReader stream = new StreamReader(File.Open(@"C:\Users\Vulisha\Desktop\titl.txt", FileMode.Open)))
            {
                string fileText = stream.ReadToEnd();

                // Do your replacements
                fileText = fileText.Replace(@"č", @"c");
                fileText = fileText.Replace(@"ć", @"c");
                fileText = fileText.Replace(@"š", @"s");
                fileText = fileText.Replace(@"ž", @"z");
                fileText = fileText.Replace(@"đ", @"d");
                fileText = fileText.Replace(@"Č", @"C");
                fileText = fileText.Replace(@"Č", @"C");
                fileText = fileText.Replace(@"Š", @"S");
                fileText = fileText.Replace(@"Ž", @"Z");
                fileText = fileText.Replace(@"Đ", @"D");

                using (StreamWriter writer = new StreamWriter(File.Open(@"titl.txt", FileMode.Create)))
                {
                    // You do a create because the new file will have less characters than the old one
                    writer.Write(fileText);
                }
            }
        }
    }
}

1 个答案:

答案 0 :(得分:6)

您需要更加小心放置括号。你需要

new StreamWriter(File.Open(@"titl.txt", FileMode.Create), Encoding.Unicode)

但你写了

new StreamWriter(File.Open(@"titl.txt", FileMode.Create, Encoding.Unicode))

看到区别?