0

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.

Farhad
  • 4,119
  • 8
  • 43
  • 66
Iasha
  • 77
  • 1
  • 8
  • What is contents of `ConfigurationSettings.AppSettings["RapServer"];` and `ConfigurationSettings.AppSettings["importDir"];` ? – SᴇM Sep 19 '17 at 10:44
  • The asterisk is not a valid character in a filename used by ReadAllText, it is a wildcard used to match multiple files If you want to read multiple files you will need to use the directory methods to get a list of matching files & read them one by one. – PaulF Sep 19 '17 at 10:44
  • 2
    A single filename may not contain a `*` – Bill Tür stands with Ukraine Sep 19 '17 at 10:44
  • If you are facing this kind of problems, just try to create file or folder with that name you want to create. – SᴇM Sep 19 '17 at 10:46
  • 1
    Try to create a file with *. You won't be allowed. – Karthick Raju Sep 19 '17 at 10:46
  • 1
    Also note that .Newt provides a method to join parts of file path & filename without using hard coded separators [Path.Combine](https://msdn.microsoft.com/en-us/library/fyy7a5kt(v=vs.110).aspx) or [this version](https://msdn.microsoft.com/en-us/library/dd784047(v=vs.110).aspx) – PaulF Sep 19 '17 at 10:52
  • Note that if you want to match a pattern when retrieving file(s), there's a solution for that. See, for example: https://stackoverflow.com/questions/3775828/get-files-from-directory-with-pattern – benichka Sep 19 '17 at 10:55

1 Answers1

4

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

Matthias Burger
  • 5,549
  • 7
  • 49
  • 94