My code in C# (asp.net MVC)
StreamWriter tw = new StreamWriter("C:\\mycode\\myapp\\logs\\log.txt");
// write a line of text to the file
tw.Write("test");
The file is created but is empty. No exception is thrown. I have never seen this before and I am stuck here; I just need to write some debugging output.
Please advise.
StreamWriter is buffered by default, meaning it won't output until it receives a Flush() or Close() call.
You can change that by setting the AutoFlush property, if you want to. Otherwise, just do:
StreamWriter tw = new StreamWriter("C:\\mycode\\myapp\\logs\\log.txt");
// write a line of text to the file
tw.Write("test");
tw.Close(); //or tw.Flush();
You need to either close or flush the StreamWriter after finishing writing.
tw.Close();
or
tw.Flush();
But the best practice is to wrap the output code in a using statement, since StreamWriter implements IDisposable:
using (StreamWriter tw = new StreamWriter("C:\\mycode\\myapp\\logs\\log.txt")){
// write a line of text to the file
tw.Write("test");
}
Neither flushed nor closed nor disposed.
try this
using (StreamWriter tw = new StreamWriter(#"C:\mycode\myapp\logs\log.txt"))
{
// write a line of text to the file
tw.Write("test");
tw.Flush();
}
or my preference
using (FileStream fs = new FileStream( #"C:\mycode\myapp\logs\log.txt"
, FileMode.OpenOrCreate
, FileAccess.ReadWrite) )
{
StreamWriter tw = new StreamWriter(fs);
tw.Write("test");
tw.Flush();
}
Use
System.IO.File.WriteAllText(#"path\te.txt", "text");
FileStream fs = new FileStream("d:\\demo.txt", FileMode.CreateNew,
FileAccess.Write);
StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.ASCII);
int data;
sw.Write("HelloWorld");
sw.Close();
fs.Close();
The problem is when StreamWriter Object is created with reference of FileStream Object , SW object will be always expecting some data till SW object is Closed.
So After using sw.Close();
Your Opened File will get closed and get ready for showing Output.
Ya in VB.net this was not needed but it seems with CSharp you need a Writer.Flush call to force the write. Of course Writer.Close() would force the flush as well.
We can also set the AutoFlush Property of the StreamWriter instance:
sw.AutoFlush = true;
// Gets or sets a value indicating whether the StreamWriter
// will flush its buffer to the underlying stream after every
// call to StreamWriter.Write.
From: http://msdn.microsoft.com/en-us/library/system.io.streamwriter.autoflush(v=vs.110).aspx
an alternative
FileStream mystream = new FileStream("C:\\mycode\\myapp\\logs\\log.txt",
FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter tw = new StreamWriter(mystream);
tw.WriteLine("test");
tw.close();
Try to close the file or add \n to the line such as
tw.WriteLine("test");
tw.Close();
Related
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.
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
1) I have created a program that has opened a twitter stream and writes everything to a file.
FileStream fs = new FileStream(#"\Database\twitterstream.txt", FileMode.Create);
TextWriter tmp = Console.Out;
StreamWriter sw = new StreamWriter(fs);
Console.SetOut(sw);
2) I have another program that I want to read said text file.
using (StreamReader sr = File.OpenText("C:\\Database\\twitterstream.txt"))
{
input = sr.ReadLine();
}
Because I want it to be in real time I am trying to have one program write, while at the same time the other program reads, however obviously it is throwing
"The process cannot access the file
'C:\Database\twitterstream.txt' because it is being used by another
process" back at me.
Is what I am trying to do possible? If so, how do I go about doing it?
Add a couple parameters to you FileStream constructor:
FileStream fs = new FileStream(
#"\Database\twitterstream.txt",
FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
See FileStream on MSDN
I am getting this error: The process cannot access the file (...) because it is being used by another process.
I have tried to use
File.WriteAllText;
StreamWriter sw = new StreamWriter(myfilepath);
sw.Write(mystring);
sw.Close();
sw.Dispose();
;
using (FileStream fstr = File.Create(myfilepath))
{
StreamWriter sw = new StreamWriter(myfilepath);
sw.Write(mystring);
sw.Close();
sw.Dispose();
fstr.Close();
}
All I am trying to do is to access a file, write on it, then close it. I might be making a silly mistake but I would like to understand what I am doing wrong and why. How to make sure that the file is closed and not to cause this error again.
Helped by the answers so far I did this:
using (FileStream fstr = File.Open(myfilepath,FileMode.OpenOrCreate,FileAccess.ReadWrite))
{
StreamWriter sw = new StreamWriter(fstr);
sw.Write(mystring);
sw.Close();
}
It seems to be better because it seems to close/stop the process of my file if I try to access another file on the second time I access the page. But if I try to access the same file on a second time, it gives me the error again.
Why not just use:
System.IO.File.WriteAllText(myfilepath, mystring");
That should not lock your file.
Internally WriteAllText uses FileShare.Read and releases that lock as soon as it is done writing.
"because it is being used by another process" that's the clue. Do you by chance have the file open in Notepad or something?
You may need to set the sharing mode when you open the file to allow readers, and ask only for the permission you need (write access).
http://msdn.microsoft.com/en-us/library/5h0z48dh.aspx
I would like to thank everyone for the help.
In fact, apart from this code I found out that I had a stremReader still opened somewhere else after the code above. At the end I changed the code I had before for this:
using (FileStream fstr = File.Open(myfile, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
StreamWriter sw = new StreamWriter(fstr);
sw.Write(mystring);
sw.Flush();
sw.Dispose();
}
and on my StreamReader I did this:
StreamReader sr = new StreamReader(myfile);
string sometext = sr.ReadToEnd();
sr.Dispose();
I could also use this:
File.ReadAllText(myfile);
If there is something that I could have done in a better way please tell me.
Thank you very much.
Try this
FileStream fs = new FileStream(myfilepath, FileMode.Create, FileAccess.Write);
byte[] bt = System.Text.Encoding.ASCII.GetBytes(mystring);
fs.Write(bt, 0, bt.Length);
fs.Close();
I am trying to save a file using DialogResult and StringBuilder. After making the text, I am calling the following code to save the file:
if (dr == DialogResult.OK)
{
StreamWriter sw = new StreamWriter(saveFileDialog1.FileName);
sw.Write(sb.ToString());
sw.Close();
}
I tried to add the second parameter to StreamWriter as Encoding.UTF8 but since the first argument is a string rather than a Stream, it does not compile it.
How can I convert that string to a stream to be able to pass the second parameter as Encoding?
The reason for this, is that somewhere in my text I have µ but when the file is saved it shows like μ so the µ is getting screwd!
Thanks
Just wrap it in a FileStream.
StreamWriter sw = new StreamWriter(
new FileStream(saveFileDialog1.FileName, FileMode.Open, FileAccess.ReadWrite),
Encoding.UTF8
);
If you want to append, use FileMode.Append instead.
You should also call Dispose() on a try/finally block, or use a using block to dispose the object when it exceeds the using scope:
using(
var sw = new StreamWriter(
new FileStream(saveFileDialog1.FileName, FileMode.Open, FileAccess.ReadWrite),
Encoding.UTF8
)
)
{
sw.Write(sb.ToString());
}
This will properly close and dispose the streams across all exception paths.
UPDATE:
As per JinThakur's comment below, there is a constructor overload for StreamWriter that lets you do this directly:
var sw = new StreamWriter(saveFileDialog1.FileName, false, Encoding.UTF8);
The second parameter specifies whether the StreamWriter should append to the file if it exists, rather than truncating it.
There is a constructor for filename, appendMode, encoding.
With a proper using block it looks like:
if (dr == DialogResult.OK)
{
using (StreamWriter sw = new StreamWriter(saveFileDialog1.FileName,
false, Encoding.UTF8))
{
sw.Write(sb.ToString());
//sw.Close();
}
}
There is a StreamWriter(string path, bool append, Encoding encoding) constructor - you could just explicitly specify the append flag too?
I said you ought to wrap your StreamWriter in a using too, i.e.
if (dr == DialogResult.OK)
{
using(StreamWriter sw = new StreamWriter(saveFileDialog1.FileName, false, Encoding.UTF8)) {
sw.Write(sb.ToString());
sw.Close();
}
}
although realistically this won't make any difference here. This effectively puts a try/finally around the code so that the StreamWriter will get cleaned up (it'll call sw.Dispose() even if an exception gets thrown in the meantime. (Some people will say this also means you no longer need the .Close since the Dispose will take care of that too but I prefer to have it anyway.)
setting UTF8 encoding working with Arabic font is the best thing I did:
using (var sw = new StreamWriter(
new FileStream(temporaryFilePath,
FileMode.Create,
FileAccess.ReadWrite),
Encoding.UTF8))
{
sw.Write(sb.ToString());
}
)
The easiest way is to use the right constructor.
StreamWriter(String, Boolean, Encoding)
Initializes a new instance of the StreamWriter class for the specified file by using the specified encoding and default 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.
C#
public StreamWriter (string path, bool append, System.Text.Encoding encoding);