0

I get this error when trying to create a file using Filestream in C#.

When i use :

{ 
  string loc1 = @"C:\Users\www14\AiLog\Fitness:200.txt";

  FileInfo fi = new FileInfo(loc1);

 using (FileStream fs = fi.Create())
}                

File in a directory : C:\Users\www14\AiLog\Fitness:200.txt is succesfully created , and appears.

However, i need this number 200 to be a variable, not a handwritten number, so i tried following :

            string loc1 = @"C:\Users\www14\AiLog\";

            string loc3 ="Fitness:"+BestNetworkFitness.ToString()+".txt";

            string loc2 = Path.Combine(loc1, loc3);


            FileInfo fi = new FileInfo(loc2);

            using (FileStream fs = fi.Create())
            { }

Then DirectoryNotFoundException: Could not find a part of the path "C:\Users\www14\AiLog\Fitness:3.73398.txt".

It seems like whenever i try to use a variable in a name, it breaks.

EDIT : oh thanks for pointing out , my loc1, loc2 was messed up. Also i deleted the ':' and it works now !

  • 4
    you create FileInfo using loc1 not loc2? – Pablo notPicasso Aug 19 '19 at 10:46
  • _"File in a directory : C:\Users\www14\AiLog\Fitness:200.txt is succesfully created"_ - is it though? Or does a file "Fitness" get created, with an Alternate Data Stream named "200.txt"? This code won't throw that exception though, as `new FileInfo(loc1)` doesn't contain the "Fitness:3.73398.txt" part. Please read [ask] and create a [mre]. Don't hack at your code and post it, hoping that it still represents the original problem. – CodeCaster Aug 19 '19 at 10:49
  • 2
    In first snippet you use `loc2` instead of `loc1`, in the second snippet vice versa. Please provide valid code. Also `:` is prohibited in file name so your code should fail with `Illegal characters in path`. – Maxim Aug 19 '19 at 10:55
  • @Maxim no, it doesn't fail. Run the code in a directory that exists. A file named "Fitness" will be created. Then if you run `dir /R` on that directory, you'll see `Fitness:200.txt:$DATA` as Alternate Data Stream. The code simply isn't a [mre]. – CodeCaster Aug 19 '19 at 11:10
  • @CodeCaster, `new FileInfo("E:\tmp\new:200.txt").Create()` gives me `Illegal characters in path`, I've tested it. Colon is invalid character. – Maxim Aug 19 '19 at 14:36

1 Answers1

0

You are trying to create using loc1, not loc2.

Also, on windows ':' is not a valid char in a filename, at least not when I try it.

David Mårtensson
  • 7,550
  • 4
  • 31
  • 47