Home > Mobile >  C# File.AppendAllText path parameter change itself
C# File.AppendAllText path parameter change itself

Time:11-18

I'm trying to use System.IO.File function like AppendAllText(string path, string content)

I have a project located on my Desktop (test project) and a file located on my desktop too

and here is my main function:

    static void Main(string[] args)
    {
        string path = @"‪C:\Users\Joevin\Desktop\MyFile.txt";
        string message = "Hello World !";
        File.AppendAllText(path, message);
    }

Based on what I have seen on the C# Documentation it should append my message on my txt file

But if I run my project, I have this error:

System.IO.IOException: 'The syntax of the file, directory or volume name is incorrect.: 'C:\Users\Joevin\Desktop\MyProject\MyProject\bin\Debug\net5.0\‪C:\Users\Joevin\Desktop\MyFile.txt''

So, it's appeared that when the function AppendAllText is called the path that I give is now the path of the executable generated my path stored in the "path" variable.

And i have the same error with others System.IO.FIle function that take a path as parameter

I feel that the problem is on my way to give the path to the function but I don't know how.

Can someone explain me why and how I can fix it?

CodePudding user response:

You probably copied the value for your path variable from somewhere and it contains (in the current codepage) not visible characters. It causes Path.GetFullPath to interpret your path as a relative path.

Since you copied your actual code in your question I copied your line into notepad and changed the codepage to ansi and it reveals the hidden characters

@"‪C:\Users\Joevin\Desktop\MyFile.txt";

CodePudding user response:

Path seems to be wrong in your case.

You can use the below code to get the desktop path.

string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);



string path = Path.Combine(desktopPath, “MyFileName.txt”);

And then use the Path.Combine method to get the complete file path and pass to the AppendAllText method.

  • Related