简体   繁体   中英

Reading/Writing doesn't recognize characters from/to .txt file C#

I have a problem when I want to read/write these characters (á ð é í ó ú ý þ æ ö) from/to txt file.

I try it with FileStream, and in the both case I encode this to these characters (ß Ú Ý ¾ · ² Ÿ µ ÷)

TxtFileModelInfo modelInfo = new TxtFileModelInfo();
TxtExporter export = new TxtExporter(modelInfo);
try
{                
    using (var outstream = new FileStream(fileName, FileMode.Create))
    {
        foreach (var obj in objects)
        {
            export.ExportObject(obj, outstream);
        }
    }                
}

TxtFileModelInfo modelInfo = new TxtFileModelInfo();
TxtImporter importer = new TxtImporter(modelInfo);
try
{                                               
    using (var instream = new FileStream(fileName,FileMode.Open))
    {                
      List<ApplicationObject> objects = importer.ImportFromStream(instream);
      if (objects != null && objects.Count > 0)
      {
          return objects;
      }
      else
      {
          Console.WriteLine(@"Object could not be readed from file {0}", 
          fileName);
      }                
  }                

}

If anybody have some tips, I would be grateful.

FileStream reads or writes only primitive types (like byte array), you will need a StreamReader and a StreamWiter to use any encoding.

For example to read data, you would use it like this:

using(var instream  = new FileStream(filename,FileMode.Open)) {
    using(var sr = new StreamReader(instream, System.Text.Encoding.UTF8)) {
        //do your work here
    }
}

Writing to a file is the same, except that you use a StreamWriter :

using(var outstream = new FileStream(filename,FileMode.Create)) {
    using(var sw = new StreamWriter(outstream, System.Text.Encoding.UTF8)) {
        //do your work here
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM