Overwrite output in txt file C# in console application - c#

if (string.IsNullOrEmpty(indata))
{
StreamWriter sw = new StreamWriter(#"c:\arjun.txt", true);
sw.WriteLine("0");
sw.Close();
}
This is my code. How can I overwrite a result in arjun.txt file I need single result.

The true part means "append" - either just get rid of it entirely, in which case you'll use the StreamWriter constructor overload which overwrites by defalut, or change true to false.
Or preferably, just use:
File.WriteAllLines(#"c:\argun.txt", new[] {"0"});
When you can specify all the data in one go, the convenience methods in File are really helpful.

Related

If no text to write via StreamWriter, then discard (do not create) the file

I am using the StreamWriter to create a file and to write some text to that file. In some cases I have no text to write via StreamWriter, but the file was already created when StreamWriter was initialized.
using (StreamWriter sw = new StreamWriter(#"C:\FileCreated.txt"))
{
}
Currently I am using the following code, when StreamWriter is closed, to check if the FileCreated.txt content is empty, if it is delete it. I am wondering if there is a more elegant approach than this (an option within StreamWriter perhaps)?
if (File.Exists(#"C:\FileCreated.txt"))
{
if (new FileInfo(#"C:\FileCreated.txt").Length == 0)
{
File.Delete(#"C:\FileCreated.txt");
}
}
By the way, I must open a stream to write before I can check if there is any text because of some other logic in the code.
If you want to take input from the user bit by bit, you can make your source a StringBuilder, and then just commit to disk when you're done
StringBuilder SB = new StringBuilder();
...
SB.AppendLine("text");
...
if(SB.Length > 0)
File.WriteAllLines(SB.ToString());
Delaying opening the file until the first output would solve this problem, but it might create a new one (if there's a permission error creating the file, you won't find out until later, maybe when the operator is no longer at the computer).
Your current approach is decent. I don't see the need to test File.Exists, though, if you just closed a stream to it. Also consider the race condition:
You find that the file is zero-length
Another process writes to the file
You delete the file
Also consider that you might have permission to create a file, and not to delete it afterwards!
Doing this correctly requires using the raw Win32 API, as I described in a previous answer. Do note that a .NET stream could be used for the first file handle, as long as you specify the equivalent of FILE_SHARE_WRITE.
Revisit your assumptions, i.e. that you must open the stream before checking for content. Simply reorganize your logic.

difference between isoFileWriter.Write() and isoFileWriter.WriteLine()

When we use isolated storage in c# we have two functions from isoFileWriter. can someone explain the difference between isoFileWriter.Write() and isoFileWriter.WriteLine()
I am using below code:
IsolatedStorageFile myspace = IsolatedStorageFile.GetUserStoreForApplication();
myspace.CreateDirectory("Emotions");
using (var isoFileStream = new IsolatedStorageFileStream("Emotions\\history.txt", FileMode.OpenOrCreate, myspace))
{
using (var isoFileWriter = new StreamWriter(isoFileStream))
{
isoFileWriter.WriteLine();
}
}
This is StreamWriter.Write and StreamWriter.WriteLine.
The main difference between the two methods is that WriteLine will write a new line to the file, where Write will just write the data (without a new line character).
Calling isoFileWriter.WriteLine() will just write a new line to the file. If you were to call WriteLine while passing a parameter, ie: isoFileWriter.WriteLine("Foo"), it would write Foo followed by a new line. isoFileWriter.Write("Foo"), on the other hand, would just write Foo without the new line character.
Write() vs WriteLine()
That typical of text stream. The difference is WriteLine writes a new line after the text
iso.Write('a');
iso.Write('b');
will output ab
iso.WriteLine('a'); //puts a new line after a
iso.Write('b'); //the next output will be on the same line as b
will output
a
b
The class System.IO.StreamWriter is used to write characters to a stream in a specific encoding. I believe that it is better to use the class StreamWriter to append or write text to a specific file and control the writer (class) later.
Structure
Consider having a StreamWriter called _TextWriter created using the following example
StreamWriter _TextWriter = new StreamWriter(Path)
and another StreamWriter called _TextWriter2 created using the following example
StreamWriter _TextWriter2 = new StreamWriter(Path, true);
If you may notice, our StreamWriter called _TextWriter2 has got two arguments: Path and a boolean true
Using true here simply tells the class that it will be used to APPEND characters to a file that the class may create or already exists. Otherwise, if you leave this blank or insert false the file will be overwritten.
Here's an example
Consider having a file name Path which contains TWO lines with the following content
This is the first line
This is the second line
By using the following code, you'll only have ONE line in your document (Path) which will be Hello
_TextWriter.WriteLine("Hello");
By using the following code, you'll have THREE lines in your document (Path) representing the following content:
This is the first line
This is the second line
Hello
_TextWriter2.WriteLine("Hello");
Now let's move to your question, what is the difference between Write() and WriteLine()
Write() and WriteLine()
The answer is simple, using the method Write() will write characters to the last available line to a specific stream if you have true set up as a boolean for append but will overwrite the content of a specific file if you leave the boolean append blank or set it to false.
Here's an example
Consider the following
You have a file name D:\MyDocument.txt
The file contains the following content
This is my first line
This is my second line
You have the following code :
StreamWriter _TextWriter = new StreamWriter(#"D:\MyDocument.txt");
_TextWriter.Write("Hello");
_TextWriter.Close(); //Save and Close the StreamWriter
What do you expect to happen?
The contents of the file D:\MyDocument.txt will change to the following
Hello
This is because you did not specify whether you want to append or not in the above code and because the default value for append is false, the StreamWriter will not append to the file and thus the file will be overwritten by the new content.
Another Example
Consider the following
You have a file name D:\MyDocument.txt
The file contains the following content
This is my first line
This is my second line
You have the following code :
StreamWriter _TextWriter = new StreamWriter(#"D:\MyDocument.txt", true);
_TextWriter.Write("Hello");
_TextWriter.Close(); //Save and Close the StreamWriter
What do you expect to happen?
The contents of the file D:\MyDocument.txt will change to the following
This is my first line
This is my second lineHello
The file was not overwritten by the word Hello because you have set the boolean append to true but did you notice this? The second line of the file has changed to
This is my first line
This is my second lineHello
This means that Hello was appended to the last line available, this is because you have used Write() which will append the text to the last line available.
Summary
So, if you would not like this to happen, you may use WriteLine() which will create a line at the end of the file first. Then, append or overwrite the file with the characters you specify.

C# add text to text file without rewriting it?

Let's say I have the following code:
StreamWriter sw = new StreamWriter(File.OpenWrite(Path));
sw.Write("Some stuff here");
sw.Dispose();
This code replaces the contents of the file with "Some stuff here," however I would like to add text to the file rather than replacing the text. How would I do this?
You could use the File.AppendAllText method and replace the 3 lines of code you have with:
File.AppendAllText(Path, "blah");
This way you don't have to worry about streams and disposing them (even in the event of an exception which by the way you are not doing properly) and the code is pretty simple and straightforward to the point.
You need to tell the StreamWriter you want to append:
var sw = new StreamWriter(path, true);
File.OpenWrite doesn't support appending.
Check out System.IO.File.AppendAllText
http://msdn.microsoft.com/en-us/library/ms143356.aspx
You can do what you want doing something like
File.AppendAllText(path, text);
There is a StreamWriter constructor which takes a bool as the 2nd parameter, which instructs the writer to append if true.
Use the append parameter:
StreamWriter sw = new StreamWriter(Path, true);
http://msdn.microsoft.com/en-us/library/36b035cb.aspx
To append text to a file, you can open it using FileMode.Append.
StreamWriter sw = new StreamWriter(File.Open(Path, System.IO.FileMode.Append));
This is just one way to do it. Although, if you don't explicitly need the StreamWriter object, I would recommend using what others have suggested: File.AppendAllText.

How to write to a text file until the application is closed

I would like to write to a text file, but I have small problem. When use the code below, it writes just once.
StreamWriter fileWriter = new StreamWriter("test.txt");
fileWriter.WriteLine(jointHead.Position.X);
fileWriter.Close();
When I write like this:
Debug.WriteLine(jointHead.Position.X);
it writes the X position until I close the application. How can I write to a text file like I write in Debug mode until I close the application. If I take fileWrite.Close() from where it stays, the program doesnt work.
Thank you...
From your description I am assuming that the code snippets you give are in a loop.
It's likely that you will get better performance by moving the file open/close outside of the loop (which will also cure your problem).
I you really want to keep opening/closing the file every time, then specify the append flag.
using (var fileWriter = new StreamWriter("test.txt", true))
{
fileWriter.WriteLine(jointHead.Position.X);
}
Try
StreamWriter fileWriter = new StreamWriter("test.txt", true);
fileWriter.WriteLine(jointHead.Position.X);
fileWriter.Close();
This will allow text written to be appended to the end of the file.
At the moment your writing from the beginning each time.
edit
If you wish to clear the file at the start of the application then just perform the following:
StreamWriter fileWriter = new StreamWriter("test.txt");
fileWriter.Write("");
fileWriter.Close();
I'd rather suggest you to use some sort of logger with a stringbuilder.
public class Logger {
private StringBuilder sb;
public Logger() {
sb = new StringBuilder();
}
public Log(String log) {
sb.Append(log).AppendLine();
}
public void Flush() {
File.WriteAllText(String.Format(#"D:\Logs\Log at {0:yyyy-MM-dd HH:mm:ss}.txt", DateTime.Now), sb.ToString());
sb.Clear();
}
}
This class is much more elegant and reusable solution. It is really acceptable if your target log is not very big.
Keep the stream writer open. But call Flush after the WriteLine call.
Alternatively you can open the file for appending, instead of recreating it for each line.
You might also want to look into an existing logging framework. There are many existing ones, no need to reinvent the wheel. Personally I'd use Common.Logging with a backend of your choice.
that constructor of the streamwriter will delete test.txt if it already existed. so every time that bit of code gets executed it will delete the file text.txt that it created earlier. instead, use the overload for the constructor of streamwriter that takes an additional bool to append to the existing test.txt file instead of replacing it:
StreamWriter fileWriter = new StreamWriter("test.txt", true);
alternatively, you could go with the File.AppendAllLines method to append your text to the file. then you don't need to worry about closing the file handle and the method name itself clearly states what's going to happen. to me this would be more convenient and not as obscure as the overloaded streamwriter constructor.
or alternatively, you could go for a logging framework like NLog. in that case NLog will take care of all your file operations so you're free of worries there then. also, you could configure NLog to write to whatever you like, like your file or, as you mentioned, the debug output window, or the event log, etc etc. also, you can bet on any file operations probably being a whole lot more efficient than your own implementation.

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)

Categories