Why Console.WriteLine in ASP.NET application not writing to file? - c#

I was doing some trials on the basis of the following Q&A: Where does Console.WriteLine go in ASP.NET?.
The code I tried goes like below:
var fs = new System.IO.FileStream(#"D:\log.txt", System.IO.FileMode.Append);
var tr = new System.IO.StreamWriter(fs);
Console.SetOut(tr);
Console.WriteLine("My Default Debugging");
fs.Close();
Here I am setting the FileStream fs to StreamWriter tr and in turn setting it as Console.Out by calling Console.SetOut(). So, by that I am expecting it to write to the file by Console.WriteLine(). Though my file gets created, it is empty.
What can be the thing I am missing here?

try tr.WriteLine("string"); instead.

var fs = new System.IO.FileStream(#"D:\log.txt", System.IO.FileMode.Append);
var tr = new System.IO.StreamWriter(fs);
Console.SetOut(tr);
Console.WriteLine("My Default Debugging");
tr.Close();
fs.Close();
Maybe it's because you didn't close the StreamWriter before you closed the FileStream?

Becuase Console.WriteLine() doesn't do that?
Writes the specified data, followed by the current line terminator,
to the standard output stream.

Related

Create and write file txt

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

StreamWriter limit in C# in text file

I have an array list which contains 100 lines.
When i try to export it into a text file (txt), the output is only 84 lines and it stops in the middle of the 84th line.
When I looked at the file size it showed exactly sharp 4.00KB as if there is some kind of a limit to the stream writer. I tried using different parameters etc. but it kept happening.
Here is the code:
FileStream fs = new FileStream(path, FileMode.Create);
StreamWriter sw = new StreamWriter(fs);
ArrayList chartList = GetChart(maintNode);
foreach (var line in chartList)
{
sw.WriteLine(line);
}
fs.Close();
Console.WriteLine("Done");
Thanks for the help!
You need to call StreamWriter.Flush or set StreamWriter.AutoFlush to true. That said, if you use using statment, everything should work fine.
using(StreamWriter sw = new StreamWriter(fs))
{
ArrayList chartList = GetChart(maintNode);
foreach (var line in chartList)
{
sw.WriteLine(line);
}
}
Using statement calls Dispose which will flush the buffer to the FileStream and also closes the file stream. So you don't need to close it manually.
Then I recommend List<T> over ArrayList. ArrayList shouldn't be used, it is not type safe and should be avoided if you're in .Net2.0 or greater.
Also consider using File.WriteAllLines method, so that you don't need these many lines of code. Everything is managed by WriteAllLines method itself.

using StreamWriter in .NET

I have a console application which writes details of the processed jobs into .txt file. I use this code to do it:
StreamWriter jp = new StreamWriter(jobsProcessed);
jp.WriteLine(DateTime.Now.ToString());
jp.WriteLine(info);
jp.WriteLine("------");
jp.Close();
Unfortunately every time a job is being processed new "info" string replaces the previous one. Is there any method to add new text to the end or beginning of the text file?
You can use StreamWriter Constructor (String, Boolean), where second boolean parameter indicates either the data has to be appended to the already available one or not.
And also avoid calling Close and use using statement
using(StreamWriter jp = new StreamWriter(jobsProcessed))
{
jp.WriteLine(DateTime.Now.ToString());
jp.WriteLine(info);
jp.WriteLine("------");
//jp.Close(); //NO NEED MORE
}
The good about this that even if exception occures, which can happen, the stream will be Disposed, by the way.
There is an overload to the StreamWriter constructor which takes a second parameter called append;
using (StreamWriter jp = new StreamWriter(jobsProcessed, true))
{
jp.WriteLine(DateTime.Now.ToString());
jp.WriteLine(info);
jp.WriteLine("------");
}
It's also better practice to wrap your StreamWriter up in a using block like above.
StreamWriter jp = new StreamWriter(jobsProcessed,true);
Second parameter
//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.
http://www.dotnetperls.com/streamwriter
http://social.msdn.microsoft.com/Forums/zh/clr/thread/17cd8ccf-7e53-41de-b4cc-221da70405a4
Just amend this:
StreamWriter jp = new StreamWriter(jobsProcessed);
To this:
StreamWriter jp = new StreamWriter(jobsProcessed, true);
// using (StreamWriter jp = new StreamWriter(jobsProcessed)) Overwrites, not good for you!
using (StreamWriter jp = new StreamWriter(jobsProcessed, true)) // Appends, good for you!
{
jp.WriteLine(DateTime.Now.ToString());
jp.WriteLine(info);
jp.WriteLine("------");
}
But you could semplify your code like so:
String[] content = File.ReadAllLines(jobsProcessed);
String[] newContent = new String[3];
newContent[0] = DateTime.Now.ToString();
newContent[1] = info;
newContent[2] = "------";
File.AppendAllLines(jobsProcessed, newContent);

Streamwriter is cutting off my last couple of lines sometimes in the middle of a line?

Here is my code. :
FileStream fileStreamRead = new FileStream(pathAndFileName, FileMode.OpenOrCreate, FileAccess.Read, FileShare.None);
FileStream fileStreamWrite = new FileStream(reProcessedFile, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None);
StreamWriter sw = new StreamWriter(fileStreamWrite);
int readIndex = 0;
using (StreamReader sr = new StreamReader(fileStreamRead))
{
while (!sr.EndOfStream) {
Console.WriteLine("eof" + sr.EndOfStream);
readIndex++;
Console.WriteLine(readIndex);
string currentRecord = "";
currentRecord = sr.ReadLine();
if (currentRecord.Trim() != "")
{
Console.WriteLine("Writing " + readIndex);
sw.WriteLine(currentRecord);
}
else {
Console.WriteLine("*******************************************spaces ***********************");
}
}
It is cutting off 2 lines with one test file and half a line, and then 1 line and half a line with the other test file I am running it against.
I am not a streamreader/writer expert you can probably see.
Any ideas or suggestions would be greatly appreciated as this is driving me batty. I am sure it is me using these incorrectly.
You are missing Flush/Close or simply using for your writer.
using(FileStream fileStreamWrite =
new FileStream(reProcessedFile, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None);
{
using(StreamWriter sw = new StreamWriter(fileStreamWrite))
{
// .... write everything here
}
}
Right after the closing brace of the using statement, do this:
sw.Flush();
sw.Close();
There, that should do it.
You need to Flush your StreamWriter. A StreamWriter has a buffer, and it writes to disk only when the buffer is full. By flushing at the end you make sure all the text in the buffer is written to the disk.
In addition to other answers (use using, and/or flush/close), would say that they do not actually respond to the question: "why it may cut several lines."
I have an idea on subject that it is related to a fact that you use StreamReader and call EndOfStream twice: in a while loop header, and another inside it.
The only possible way of understanding if the stream ends is try to read some data from it. So I suspect EnfOfStream does it, and reading it twice, may create a problem in stream processing.
To resolve an issue:
Or use simple TextReader, considering that you are reading text file (seems to me)
Or change your logic to call only once, so no more call to Console.WriteLine("eof" + sr.EndOfStream);
Or change your logic, so do not use EndOFStream at all, but read line by line till the line is null.
You're not using StreamWriter properly. Also, since you're always reading lines, I would use a method that already does all that for you (and manages it properly).
using (var writer = new StreamWriter("path"))
{
foreach(var line in File.ReadLines("path"))
{
if (string.IsNullOrWhiteSpace(line))
{ /**/ }
else
{ /**/ }
}
}
... or ...
/* do not call .ToArray or something that will evaluate this _here_, let WriteAllLines do that */
var lines = File.ReadLines("path")
.Select(line => string.IsNullOrWhiteSpace(line) ? Stars : line);
var encoding = Encoding.ASCII; // whatever is appropriate for you.
File.WriteAllLines("path", lines, encoding);

Writing in files ASP.NET C# and NOT locking them afterwards

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

Categories