Create and write file txt - c#

How can I create and then modify writing on this file?
string fileName = #"C:\...\MioFile.txt";
In main:
File.CreateText(fileName);
Then when I would edit the file by adding text.
StreamWriter writer = new StreamWriter(fileName);
sw.WriteLine("Hello"+variable);
sw.Close();
But the file is empty and I cannot write anything.
I would like create a file.txt and I would like for this file to always add new information every time I call it in writing mode. A kind of "log file".

Use File.AppendAllText instead of StreamWriter. Its simple:
File.AppendAllText(filename, "Hello"+variable);

You have sw.WriteLine, But your streamwriter is called "writer". That might be the problem.

I like to use the "using" statements:
//full path
var fileName = #"C:\Users\...\Desktop\newFile2.txt";
//Get the stream in FileMode.Append (will create or open)
using (var fileStream = new FileStream(fileName,FileMode.Append))
{
//pass the fileStream into the writer.
using (var writer = new StreamWriter(fileStream))
{
writer.WriteLine("{0} => file appended", DateTime.Now);
}//dispose writer
}//dispose fileStream

Related

Overwriting file in c# using stream writer

I am trying to write a html file using stream writer in c#, it is overwriting the file if close the application and run again, but its appending when I tried to write file for different scenario without closing the application. I wants to overwrite in second case also.
using (FileStream fs = new FileStream("Report.html", FileMode.Create, FileAccess.Write))
{
using (StreamWriter w = new StreamWriter(fs, Encoding.UTF8))
{
w.WriteLine(html);
}
}
To append to the end of your file:
File.AppendAllText("Report.html", html, Encoding.UTF8);
To overwrite your file:
File.WriteAllText("Report.html", html, Encoding.UTF8);
Try explicitly closing the writer and stream instead of depending upon you using () expression to do that for you.

Working with .tmp file for writing data

I'm wondering if there is a best practice when it comes to working with .tmp file for writing data. I like to make an .tmp that will be use in the filestream and then when I close the writer, I like to rename the file. Is there a way to rename file extension?
FileStream stream2 = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite);
StreamWriter streamWriter2 = new StreamWriter(stream2);
streamWriter2.WriteLine(textToAdd);
streamWriter2.Close();
string changed = Path.ChangeExtension(fileName, .txt);
File.Move(path, changed);
Here's how I would do this:
// Build a FileInfo object for your temp destination, this gives us
// access to a handful of useful file manipulation methods
var yourFile = new FileInfo(#"C:\temp\testfile.tmp");
// open a StreamWriter to write text to the file
using (StreamWriter sw = yourFile.CreateText())
{
// Write your text
sw.WriteLine("Test");
// There's no need to call Close() when you're using usings
}
// "Rename" the file -- this is the fastest way in C#
yourFile.MoveTo(#"C:\temp\testfile.txt");
You can use Path.GetFilenameWithoutExtension to remove the extension and then just add the one you want.

Writing in an existing file using streamwriter

I want to use StreamWriter to write in a file that already exists in my project's debug folder. How can I do that? I thought StreamWriter can only write to a whole new file.
Do you mean append?
StreamWriter sw = new StreamWriter("abc.txt", true);
sw.WriteLine("test");
sw.Close();
using(var sw = new StreamWriter("yourfile.txt", true))//default location is your bin folder
{
}
Use the above overload

The process cannot access the file when using StreamWriter

Basically I want to create a file if not existing then write message to it.
if (!File.Exists(filePath + fileName))
File.Create(filePath + fileName);
StreamWriter sr = new StreamWriter(filePath + fileName,false);
How to deal with this error?
The process cannot access the file 'c:\blahblah' because it is being used by another process.
File.Create opens a FileStream (http://msdn.microsoft.com/en-us/library/d62kzs03.aspx).
As you didn't dispose it, the file remains locked and subsequent accesses to the file will fail because of this situation if these are performed from other handles (i.e. other FileStream or the whole StreamWriter).
This code demonstrates how you should work with IDisposable objects like FileStream:
if (!File.Exists(filePath + fileName))
{
File.Create(filePath + fileName).Dispose();
using(StreamWriter sr = new StreamWriter(filePath + fileName,false))
{
}
}
Why not just use the StreamWriter constructor that takes in the file name?
StreamWriter sr = new StreamWriter(filePath + fileName);
From MSDN:
The path parameter can be a file name, including a file on a Universal Naming Convention (UNC) share. If the file exists, it is overwritten; otherwise, a new file is created.
Very minor point but you could consider using Path.Combine when concatenating file names and folder paths.
Simplify your code by using single method to create and open a file:
using (FileStream fs = File.OpenWrite(path))
{
Byte[] info = new UTF8Encoding(true)
.GetBytes("This is to test the OpenWrite method.");
fs.Write(info, 0, info.Length);
}
MSDN: (File.OpenWrite Method)
Opens an existing file or creates a new file for writing.

StreamWriter is not able to write in file

My code is
System.IO.StreamWriter objStreamWriter = new System.IO.StreamWriter(File);
objStreamWriter.Write(txtEditor.Text);
objStreamWriter.Close();
txtEditor.Text = string.Empty;
I got a message The file has been modified out side of............. but my text file is empty. When in debug mode, I got a value of textEditor and path is not a problem. Am I missing some stupid things.
Thanks.
You have to verify the content of txtEditor before you write it to disk file.
string text=txtEditor.Text;
if(text.Trim.Length!=0)
{
using(System.IO.StreamWriter objStreamWriter = new System.IO.StreamWriter(File))
{
objStreamWriter.Write(text);
}
}
Use the StreamWriter by the "using" keyword for correct writing in to textfile.
using (StreamWriter writer = new StreamWriter("important.txt"))
{
writer.Write("Word ");
writer.WriteLine("word 2");
writer.WriteLine("Line");
}
Refer to the C# Using StreamWriter for more info

Categories