StreamWriter doesn't write to a file that doesn't exist
Solution 1
You're missing a constructor which takes a boolean that can aid in creating the file:
using (StreamWriter stream = new StreamWriter(filePath, false)) {
stream.Write(data);
stream.Close();
}
The logic is actually is little more complex than that, however:
public StreamWriter( string path, bool append )
Determines whether data is to be appended to the file. If the file exists and append is false, the file is overwritten. If the file exists and append is true, the data is appended to the file. Otherwise, a new file is created.
Solution 2
Why don't you just go around it the easy way, and check for file existence prior to writing to it:
public void Foo(string path, string data)
{
if (!File.Exists(path))
File.Create(path);
using (var sw = new StreamWriter(path, false))
{
// Work your magic.
sw.Write();
}
}
I'd really not make it any more complicated than that personally. Also, don't close the StreamWriter
, the using
statement disposes of it after it's served its purpose.
Solution 3
In my case I was running the program as non-admin, the file was to be written inside a folder that was created with administrator rights (even inside ProgramFiles or any non-admin location). The file is never created and you have to manually enable the Managed Debugging Assistants
exception breaks in order to see any error.
Solution was to delete the folder and create it again with my non-admin account. Also note that StreamWriter does not create directory trees, only files.
annonymously
I could be over 50 years old, or I couldn't. I could be 3 feet tall, or I couldn't. I could eat raw coffee beans, or I couldn't. I could have a pet elephant, and you wouldn't know it. That is the nature of annonimity. Spelled with double 'n' first instead of second. Yeah.
Updated on July 16, 2022Comments
-
annonymously almost 2 years
I am making a level editor for my game, and most of it is working except... When I try to save my file (XML) the file doesn't get created, and in the output box I get:
A first chance exception of type 'System.NullReferenceException'
The funny thing is that it only happens if the file doesn't exist, but it works correctly if I overwrite another file.
here is the code I'm using:
using (StreamWriter stream = new StreamWriter(filePath)) { stream.Write(data); stream.Close(); }
data is a string (this is not the problem because it works when I overwrite the file)
-
ChrisF over 12 yearsWhich line gives the
NullReferenceException
? -
annonymously over 12 yearsIt doesn't say, I think the StreamWriter must catch the exception and Debug.WriteLine the message
-
ChrisF over 12 yearsThe only thing I can think of is that the program doesn't have create permissions to the directory. Try removing the
using
(for debug purposes only) and see if you get a more meaningful exception. -
annonymously over 12 years@ChrisF nope, the exception is still not appearing, it's just being written to the output box
-
annonymously over 12 years@luisperezphd yes, they work if the file exists
-
annonymously over 12 years@ChrisF when I set a breakpoint on the line where I set data and step over to the StreamWriter part it just resumes my program.
-
Jim Mischel over 12 yearsI strongly suspect that there's something else in your code that's crashing before you get to the
StreamWriter
here. Or, perhapsfilePath
isnull
if the file doesn't already exist? On a separate note, there's no reason to callstream.Close()
if you're in ausing
. That'll be done for you automatically. -
annonymously over 12 years@JimMischel The breakpoints work right up to the line where I create the StreamWriter. filePath is not null and I have removed the using part as it was only for debugging
-
-
annonymously over 12 yearsYes, that was the first way that worked and I copy pasted my backup sorry ;)
-
annonymously over 12 yearsWell, that makes the stream append to the file, I want to replace the file
-
annonymously over 12 yearsIf the file exists I want to overwrite it, not append to it
-
ChrisF over 12 yearsI don't think this is the correct overload. The problem is not that the file is getting overwritten, but that it's not getting created in the first place.
-
Grant Thomas over 12 years@ChrisF I've taken a look and with
append
beingfalse
this constructor will always create the file if it doesn't exist. As per this: Initializes a new instance of the StreamWriter class for the specified file on the specified path, using the default encoding and buffer size. If the file exists, it can be either overwritten or appended to. If the file does not exist, this constructor creates a new file. -
aevitas over 12 yearsWhen using the
using
keyword, you don't need to callsw.Close()
, it's taken care of automatically. (which is the whole point of usingusing
in the first place) -
Luis Perez over 12 yearsWhen I run this code it creates a file if it doesn't exist. And overwrites it does exist - is that not the behavior you wanted?
-
Luis Perez over 12 yearsOk, I see, this is the way it should behave, but it's not working on your specific computer. Can you get a stack trace? Have you tried to see if you have the latest version of the .NET framework? Maybe somehow you have write but not create permission to the folder?
-
annonymously over 12 years@aevitas Actually I only used the using part for debugging to see if it would work
-
annonymously over 12 yearsI do have the latest .net framework, and I'm pretty sure I have create permissions to the folder. As for the stack trace, I'm sorry but I can't seem to debug after the error, it just resumes the program
-
Luis Perez over 12 yearsYou can try running the free filemon application to see if it gives you any more details. There is also a setting in visual studio that will freeze the application when any exception is thrown even handled ones. Finally you can add code to output the stack trace.
-
Grant Thomas over 12 yearsThe check is redundant though, so inherently makes things more complex.
-
aevitas over 12 yearsPersonally I don't think it does. Even though it may be redundant, it makes it easier to read, understand, and debug.
-
xmedeko about 6 yearsIt's not easier to read. What this code says about race conditions? What if other process deletes the file just after it's created? It error prone to race conditions. StreamWriter has to correctly create the file. Otherwise it's a bug in .NET.