0

I have simple code

using (FileStream fs = File.Create(@"newfile.txt"))
{

}

And if I give the path "E:\newfile.txt" I get the error System.IO.IOException: 'The media is write protected.'

If I give the path "C:\newfile.txt" I get no error but no file creation, even if I give the path "C:\Users\Me\Documents\newfile.txt" I get no error and no file creation.

Are these errors related, I have written to USB devices no problem before, and my C drive should not be restricted and surely the Users folder isnt restricted at all.

What am I missing?

Colin Steel
  • 1,045
  • 1
  • 11
  • 24
  • C drive is restricted by default on `Windows 10`. Which version of `Windows` are you running this code on ? Whichever version it is the `My Documents` should always be fine unless it is redirected to a network folder like most business because of roaming profiles. the error for USB drive could be locked or password protected (same as external hard drive with protection). Are you actually writing any data to the file or is it exactly how to wrote your code sample ? – Franck Jun 25 '19 at 17:57
  • So, if you create the file exactly like that: `using (FileStream fs = File.Create(@"newfile.txt"))`, can you find the file in your project's `\bin\Debug` or `\bin\Release` folder? The other path you mentioned are restricted\not-writable\wrong. – Jimi Jun 25 '19 at 18:05
  • @Franck Windows 10, exactly like the code sample, the using statement throws the exception. Documents is not a network folder. I can create files on all locations in windows explorer. – Colin Steel Jun 25 '19 at 18:12
  • @Jimi File does not create with no error in bin folders. – Colin Steel Jun 25 '19 at 18:12
  • You mean in `Debug` or `Release` folders. If the file is not created, the problem is not here. Maybe that code is never called, there's an error somewhere else etc. Put it in the `Click` handler of a Button - just that code - and try again. – Jimi Jun 25 '19 at 18:14
  • @Jimi the code does reach here, I can debug through it. (well, to it, not through it) – Colin Steel Jun 25 '19 at 18:16
  • @ColinSteel Then your `Visual Studio` must not be running as an `Administrator` that's the only thing i can see. – Franck Jun 25 '19 at 18:24
  • Did you move that exact code, on its own, to a `Button.Click` event? Do and see the results. If your solution configuration is `Debug`, you'll find it in `[\YourProjectName\bin\Debug]` – Jimi Jun 25 '19 at 19:09

1 Answers1

0

Perhaps this might work:

string path = @"C:\Users\Me\Documents\newfile.txt"
File.AppendAllText(path,new[] {"Your text goes here"});

This will create the file if it does not exist or write to the existing one.

See Also: Create a .txt file if doesn't exist, and if it does append a new line

B. Seberle
  • 370
  • 1
  • 8