Iasha
Iasha

Reputation: 77

c# IIllegal Characters in Path

I don't see what is wrong about the below code. It throws an error at Line 4

private void ProcessCsvsReplaceNullsWithSpaces()
{
    string server = ConfigurationSettings.AppSettings["RapServer"];
    string importDir = ConfigurationSettings.AppSettings["importDir"];
    string fileName = server + @"\" + importDir + "\\EMIR_VU_E_*.csv";
    string replacenull = File.ReadAllText(fileName);
    replacenull = replacenull.Replace("null", "");
    File.WriteAllText(fileName, replacenull);
}

Exception thrown: 'System.ArgumentException' in mscorlib.dll

Additional information: Illegal characters in path.

Upvotes: 0

Views: 3178

Answers (1)

Matthias Burger
Matthias Burger

Reputation: 5946

You can always check your path, whether it contains invalid path characters. Try iterating with the method Path.GetInvalidPathChars.

See the documentation of msdn

This lists all invalid characters. Now you can iterate your path to check if there are any chars matching that list

bool containsInvalidChars = (!string.IsNullOrEmpty(filepath) 
        && filepath.IndexOfAny(System.IO.Path.GetInvalidPathChars()) >= 0);

if this is true, you got an invalid char in your path

As a few others mentioned: your filename must not contain a * character

You also need to check, whether your filename contains invalid characters:

This is the method: System.IO.Path.GetInvalidFileNameChars()

Here you find the *:

enter image description here

Upvotes: 4

Related Questions