Issue to write to the file

Peter_1985 2,711 Reputation points
2025-01-22T02:44:54.6033333+00:00

Hi,

I used the way like

using (StreamWriter sw = new StreamWriter(@"z:/oup2.txt", allowappend, Encoding.Unicode))

to write to the output text file but it does work well. Is it being affected by the file type (like Ansi or Unicode one)?

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,263 questions
{count} votes

Accepted answer
  1. Jiachen Li-MSFT 33,371 Reputation points Microsoft Vendor
    2025-01-22T07:38:10.2033333+00:00

    Hi @Peter_1985 ,

    If inp2.txt was originally created with a different encoding (e.g., ANSI or UTF-8), then opening it with Encoding.Unicode could misinterpret the characters.

    Try using using (StreamReader sr = new StreamReader(@"z:/inp2.txt", true)) to auto-detect encoding.

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Jiachen Li-MSFT 33,371 Reputation points Microsoft Vendor
    2025-01-22T06:05:43.4+00:00

    Hi @Peter_1985 ,

    Yes. When you specify Encoding.Unicode, it writes the file in UTF-16 encoding. If the file was originally created with a different encoding (like ANSI), this could cause issues when appending.

    Best Regards.

    Jiachen Li


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.