Howto clear a textfile without deleting file? - c#

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.

Related

rest api output to json file in c# [duplicate]

I have a string with a C# program that I want to write to a file and always overwrite the existing content. If the file isn't there, the program should create a new file instead of throwing an exception.
System.IO.File.WriteAllText (#"D:\path.txt", contents);
If the file exists, this overwrites it.
If the file does not exist, this creates it.
Please make sure you have appropriate privileges to write at the location, otherwise you will get an exception.
Use the File.WriteAllText method. It creates the file if it doesn't exist and overwrites it if it exists.
Generally, FileMode.Create is what you're looking for.
Use the file mode enum to change the File.Open behavior. This works for binary content as well as text.
Since FileMode.Open and FileMode.OpenOrCreate load the existing content to the file stream, if you want to replace the file completely you need to first clear the existing content, if any, before writing to the stream. FileMode.Truncate performs this step automatically
// OriginalFile:
oooooooooooooooooooooooooooooo
// NewFile:
----------------
// Write to file stream with FileMode.Open:
----------------oooooooooooooo
var exists = File.Exists(path);
var fileMode = exists
? FileMode.Truncate // overwrites all of the content of an existing file
: FileMode.CreateNew // creates a new file
using (var destinationStream = File.Open(path, fileMode)
{
await newContentStream.CopyToAsync(destinationStream);
}
FileMode Enum
If your code doesn't require the file to be truncated first, you can use the FileMode.OpenOrCreate to open the filestream, which will create the file if it doesn't exist or open it if it does. You can use the stream to point at the front and start overwriting the existing file?
I'm assuming your using a streams here, there are other ways to write a file.

StreamWriter doesn't write to a file that doesn't exist

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();
}

The file is being used by another process, I must close it? How?

I am using a text file to have some data there for later purposes. So what I do is to check if file exists, if not I am creating a new file when I need. This gives me error saying that my file is still being used by a different process, but I'm not sure why that is.
This is how I do it. Here, I am checking if file exists which starts when program runs:
private void CreateLastOpenFile()
{
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
if (!File.Exists(file))
{
File.Create(file);
}
}
Now, I am adding some data to it while checking or creating a new file (I am having this in 2 places in my program):
CreateLastOpenFile();
File.WriteAllText(file, data);
What could be wrong here? I have read some examples from the Net, but didn't see anything about closing any files.
Try this. This will close the opened stream during file creation
if (!File.Exists(file))
{
FileStream str = File.Create(file);
str.Close();
}
File.Create is creating a FileStream that locks the file. You should close it. Actually, you don't even need to create a file. File.WriteAlltext will do it for you
You are not closing the stream handle that File.Create() returns.
Suggest you do not use File.Create() in your case. You can just use File.WriteAllText(file, data); - according to MSDN documentation it creates the file if it doesn't exist or overwrites the contents when file exists. After that closes the file stream.
I recommend you to create and fill with data the file in one step, using some class like StreamWriter that allows you to dispose the class, you should not have problem doing it this way, here is an example:
StreamWriter Swr = new StreamWriter(FilePath);
Swr.Write(Data);
Swr.Close();
Swr.Dispose();
//Doing the close and Dispose you get sure the file is not locked anymore
You can also use File.WriteAllText(string Path, string Data), this method does not lock the file.
If you are using below method to write the data into text file, you dont need to check if file exists and if not create it. "WriteAllText" takes cares of all these things by itself. It will create the file if not exists, write the data and close it, or overwrite the file if already exists.
File.WriteAllText(file, data);
if you are using writeAllText() or readAllText() method than close() method is not used as they closed file after reading or writing(above methods)

Saving Files c# - without overwriting?

I am saving data to a file every 60 secs, I have it saving every 60 secs ok but it deletes the previous data added. Is there a way in which it would add to the file rather than overwrite it. And without using save dialog as it is done in the background.
Any feedback is greatly appreciated
It seems opening the File in Append mode will solve your problem.
http://msdn.microsoft.com/en-us/library/3zc0w663.aspx
Try,
using (StreamWriter writer = new StreamWriter(#"C:\somefile.txt", true))
{
writer.WriteLine("Hello line..");
}
Specify FileMode.Append in the FileStream constructor.
Use File class AppendText method.
StreamWriter sw = File.AppendText("D:\\Text.txt");
sw.WriteLine("Hello");
sw.WriteLine("World");
sw.WriteLine("Test");
sw.Flush();
sw.Close();
You can use StreamWriter with append as true in the constructor.
See here.
OK as i am getting your question You are having a File And you want to save new data on that instead of replacing it
You can just open its content using stream reader.and append that data you want to insert on the file
using writer don't save file each time just append data on that file so when you just appending something on that it will not overwrite that file.

Clear the Contents of a File

How does one clear the contents of a file?
You can use the File.WriteAllText method.
System.IO.File.WriteAllText(#"Path/foo.bar",string.Empty);
This is what I did to clear the contents of the file without creating a new file as I didn't want the file to display new time of creation even when the application just updated its contents.
FileStream fileStream = File.Open(<path>, FileMode.Open);
/*
* Set the length of filestream to 0 and flush it to the physical file.
*
* Flushing the stream is important because this ensures that
* the changes to the stream trickle down to the physical file.
*
*/
fileStream.SetLength(0);
fileStream.Close(); // This flushes the content, too.
Use FileMode.Truncate everytime you create the file. Also place the File.Create inside a try catch.
The easiest way is:
File.WriteAllText(path, string.Empty)
However, I recommend you use FileStream because the first solution can throw UnauthorizedAccessException
using(FileStream fs = File.Open(path,FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
lock(fs)
{
fs.SetLength(0);
}
}
Try using something like
File.Create
Creates or overwrites a file in the
specified path.
The simplest way to do this is perhaps deleting the file via your application and creating a new one with the same name... in even simpler way just make your application overwrite it with a new file.

Categories