StreamWriter doesn't write to a file that doesn't exist - c#

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)

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.

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.

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.

Have you tried not using File.Create()? like so:
using (StreamWriter stream = new StreamWriter(filePath)) {
stream.Write(data);
stream.Close();
}

Related

File gets locked after setting attributes

I have a method which saves the object into the file. The object gets modified and saved multiple times. The problem is that when I'm trying to save object for the second time into the same file, I'm getting the UnautorizedAccessException. Here is the code:
public void Save(string path)
{
string fileName = String.Format("{0}\\{1}", path, DataFileName);
using (FileStream fs = new FileStream(fileName, FileMode.Create))
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(fs, this);
File.SetAttributes(fileName, FileAttributes.Hidden);
}
}
What's the most interesting, is that if I comment the line
File.SetAttributes(fileName, FileAttributes.Hidden);
problem disappears. How comes? And how can I solve this problem?
MSDN says this about FileMode.Create:
Specifies that the operating system should create a new file. If the
file already exists, it will be overwritten. This requires
FileIOPermissionAccess.Write permission. FileMode.Create is equivalent
to requesting that if the file does not exist, use CreateNew;
otherwise, use Truncate. If the file already exists but is a hidden
file, an UnauthorizedAccessException exception is thrown.
Which is exactly what you are seeing. So the solution seems to be either use a different mode, or as suggested in the comments, unhide -> save -> hide.

Reading file after writing it

I have a strange problem. So my code follows as following.
The exe takes some data from the user
Call a web service to write(and create CSV for the data) the file at perticular network location(say \some-server\some-directory).
Although this web service is hosted at the same location where this
folder is (i.e i can also change it to be c:\some-directory). It then
returns after writing the file
the exe checks for the file to exists, if the file exists then further processing else quite with error.
The problem I am having is at step 3. When I try to read the file immediately after it has been written, I always get file not found exception(but the file there is present). I do not get this exception when I am debugging (because then I am putting a delay by debugging the code) or when Thread.Sleep(3000) before reading the file.
This is really strange because I close the StreamWriter before I return the call to exe. Now according to the documention, close should force the flush of the stream. This is also not related to the size of the file. Also I am not doing Async thread calls for writing and reading the file. They are running in same thread serially one after another(only writing is done by a web service and reading is done by exe. Still the call is serial)
I do not know, but it feels like there is some time difference between the file actually gets written on the disk and when you do Close(). However this baffling because this is not at all related to size. This happens for all file size. I have tried this with file with 10, 50, 100,200 lines of data.
Another thing which I suspected was since I was writing this file to a network location, it could be windows is optimizing the call by writing first to cache and then to network location. So I went ahead and changed the code to write it on drive(i.e use c:\some-directory), rather than network location. But it also resulted in same error.
There is no error in code(for reading and writing). As explained earlier, by putting a delay, it starts working fine. Some other useful information
The exe is .Net Framework 3.5
Windows Server 2008(64 bit, 4 GB Ram)
Edit 1
File.AppendAllText() is not correct solution, as it creates a new file, if it does not exits
Edit 2
code for writing
using (FileStream fs = new FileStream(outFileName, FileMode.Create))
{
using (StreamWriter writer = new StreamWriter(fs, Encoding.Unicode))
{
writer.WriteLine(someString)
}
}
code for reading
StreamReader rdr = new StreamReader(File.OpenRead(CsvFilePath));
string header = rdr.ReadLine();
rdr.Close();
Edit 3
used textwriter, same error
using (TextWriter writer = File.CreateText(outFileName))
{
}
Edit 3
Finally as suggested by some users, I am doing a check for the file in while loop for certain number of times before I throw the exception of file not found.
int i = 1;
while (i++ < 10)
{
bool fileExists = File.Exists(CsvFilePath);
if (!fileExists)
System.Threading.Thread.Sleep(500);
else
break;
}
So you are writing a stream to a file, then reading the file back to a stream? Do you need to write the file then post process it, or can you not just use the source stream directly?
If you need the file, I would use a loop that keeps checking if the file exists every second until it appears (or a silly amount of time has passed) - the writer would give you an error if you couldn't write the file, so you know it will turn up eventually.
Since you're writing over a network, most optimal solution would be to save your file in the local system first, then copy it to network location. This way you can avoid network connection problems. And as well have a backup in case of network failure.
Based on your update, Try this instead:
File.WriteAllText(outFileName, someString);
header = null;
using(StreamReader reader = new StreamReader(CsvFilePath)) {
header = reader.ReadLine();
}
Have you tried to read after disposing the writer FileStream?
Like this:
using (FileStream fs = new FileStream(outFileName, FileMode.Create))
{
using (StreamWriter writer = new StreamWriter(fs, Encoding.Unicode))
{
writer.WriteLine(someString)
}
}
using (StreamReader rdr = new StreamReader(File.OpenRead(CsvFilePath)))
{
string header = rdr.ReadLine();
}

File already being accessed error

I have a few files in \AppData\Roaming that my app is writing to. I create the files when the application starts like this:
private void Form1_Load(object sender, EventArgs e)
{
DirectoryInfo _File = new DirectoryInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), #"MyApp\myfile.txt"));
}
Later, when I write to the file with a button click, I get an error saying that the file is already in use and cannot be accessed. How would I fix this?
The code to write to the file is correct because when I remove the code above and make the files myself, the application writes to them without any issues. Therefore, I dont think the problem is with the code I use to write to the files. But, here it is for reference:
var myfile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), #"MyApp\myfile.txt"));
StreamWriter sw = new StreamWriter(myfile);
sw.WriteLine(textBox1.text);
sw.Close();
Thanks in advance for any help!
There are a few concepts at play here and I am not sure that we have enough information to definitively address the root problem, but I will give you a few pointers.
You need to be aware of the FileMode, FileAccess and FileShare enumerations.
The first, FileMode, specifies what you intend to do with regard to the file's existence. There are various options, documented in the link above. mI don't think that you have a problem here, but it bears mentioning.
The second, FileAccess, concerns your intended interaction with the file (read, write, or both). If you ask for access to read, then anyone else who opens the file or had it open already (including that web browser control) must have allowed sharing with other readers.
The final one, FileShare, defines who you are willing to share access to the file with. You can specify that others can read it, others can write to it, both, or neither.
The code that you are using is accessing the file using the very simplest defaults, which may be incompatible with the WebBrowser's access mode. Here's what I'd suggest instead:
var myfile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), #"MyApp\myfile.txt"));
using (var fs = new FileStream(myfile, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite)) {
using (var sw = new StreamWriter(fs)) {
// You probably want to move to the end of the file before writing...
fs.Seek(0, SeekOrigin.End);
sw.WriteLine(textBox1.text);
sw.Close();
}
}
This very clearly expresses your intent, as well as the fact that you are willing to share with others who might read or write (we know the webbrowser will not write to the file, but for some reason maybe it is trying to open it with write intent anyway).
For file operations (as well as anytime your are accessing unmanaged resources) your best bet is to only grab a handle to the file long enough to perform the operation you want and then release it.
In your case, you are opening the resource, then trying to open it again later. Change this. Don't create the files until you are actually going to do something with it. Also, look into the USING clause. You want to release it as soon as you are done reading or writing from it.
Try to Access the FileInfo object to create/append/write files as follows, the file is already been taken by FileInfo class,
use as following,
FileInfo fi1 = new FileInfo(path);
//Create a file to write to.
using (StreamWriter sw = fi1.CreateText())
{
sw.WriteLine("Hello");
sw.WriteLine("And");
sw.WriteLine("Welcome");
}
//Open the file to read from.
using (StreamReader sr = fi1.OpenText())
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
Console.WriteLine(s);
}
}
Try using using.
using (StreamWriter sw = new StreamWriter(myfile))
{
sw.Write(textBox1.text);
}

Howto clear a textfile without deleting file?

Question: I have an ini file which I need to clear before I add info to it.
Unfortunately, if I just delete the file, the permissions are gone as well.
Is there a way to delete a file's content without deleting the file ?
String path = "c:/file.ini";
using (var stream = new FileStream(path, FileMode.Truncate))
{
using (var writer = new StreamWriter(stream))
{
writer.Write("data");
}
}
Just open the file in truncate (i.e. non-append) mode and close it. Then its contents are gone. Or use the shortcut in the My namespace:
My.Computer.FileSystem.WriteAllText("filename", "", False)
I'm not 100% sure, but you can try this:
File.WriteAllText( filename, "");
I'm not sure if this will delete, and recreate the file (in that case your permission problem will persist, or if it will clean out the file. Try it!
This should probably work:
using (File.Create("your filename"));
Here, the using does not have a block because of the ; at the end of the line. The File.Create truncates the file itself, and the using closes it immediately.

Program crashes after trying to use a recently created file. C#

So here is my code
if (!File.Exists(pathName))
{
File.Create(pathName);
}
StreamWriter outputFile = new StreamWriter(pathName,true);
But whenever I run the program the first time the path with file gets created. However once I get to the StreamWriter line my program crashes because it says my fie is in use by another process. Is there something I'm missing between the File.Create and the StreamWriter statements?
File.Create doesn't just create the file -- it also opens it for reading and writing. So the file is indeed already in use when you try to create the StreamWriter: by your own process.
StreamWriter will create the file specified by pathName if it doesn't exist, so you can simply remove the File.Exists check and simplify your your code this:
using (var writer = new StreamWriter(pathName, true))
{
// ...
}
From MSDN:
StreamWriter Constructor (Stream)
Initializes a new instance of the StreamWriter class for the specified file [...]. If the file exists, it can be either overwritten or appended to. If the file does not exist, this constructor creates a new file.
As others have mentioned, File.Create is creating a FileWriter that's holding your file open. But aside from that, there's no reason to check for file existence before trying to open the file. Just tell File.Open to open an existing file if one is there:
var outputFile = new StreamWriter(File.Open(pathName, FileMode.OpenOrCreate));
After the File.Create the stream is still open.
You could use:
File.Create(pathName).Close();
This creates the file and closes it directly.
More accepted is:
using (var file = File.Create(pathName)) {
// use the file here
// it will be closed when leaving the using block
}
Also: Why do you create a file, that you create 2 lines further in your code? The StreamWriter constructor (with append=true) will create or append the file if it does not exist.
File.Create returns a FileStream. Why don't you save that and pass it to the StreamWriter constructor instead of passing a pathname?

Categories