StreamWriter won't write to log file - c#

This code will create "output.txt" in C:\temp if it doesn't already exist. However, log.WriteLine(); doesn't work for me. When I open the file, I don't see it. Why is this?
private static string LogFile = #"C:\Temp\output.txt";
private StreamWriter log;
if (!File.Exists(#"" + LogFile))
{
log = new StreamWriter(#"" + LogFile);
}
else {
log = File.AppendText(#"" + LogFile);
}
log.WriteLine("["+DateTime.Now + "]: ");

You need to close the StreamWriter. It's best to use a using block for this, as it guarantees that the StreamWriter will be closed, even if an exception is thrown.
using (var log = GetLog()){
log.WriteLine("["+DateTime.Now + "]: ");
}
...
public StreamWriter GetLog(){
if (!File.Exists(#"" + LogFile))
{
return new StreamWriter(#"" + LogFile);
}
else {
return File.AppendText(#"" + LogFile);
}
}

Just a little improvement in code to #John Saunders answer.
using (var log = GetLog())
{
log.WriteLine("["+DateTime.Now + "]: ");
}
...
public StreamWriter GetLog()
{
return new StreamWriter(LogFile, File.Exists(LogFile));
}
The second parameter StreamWriter constructer takes determines append operation. Thus if file exists append otherwise not will do it. I think this is neater. And actually you can even do:
using (var log = new StreamWriter(LogFile, true))
{
log.WriteLine("["+DateTime.Now + "]: ");
}
Always appends, and if file does not exist creates it.

If you are always appending the same thing to the file whether or not it already exists, you don't need the conditional.
File.AppendText will create the file if it doesn't exist.
private static string LogFile = #"C:\Temp\output.txt";
using (StreamWriter sw = File.AppendText(LogFile))
{
sw.WriteLine("["+DateTime.Now + "]: ");
}
As John Saunders already said, you need to Dispose the stream writer, which will be done by putting it in a using statement.
(Documentation for StreamWriter)

Related

How to Write to a file using StreamWriter?

in my Wpf app I'm using a class Person (that is a base class), and that contains a virtual method SaveData(), and other class Client that inherits from Person. How to override method SaveData() and keeping data from base?
Class Person
public virtual void SaveData()
{
string arqName = string.Format("Person{0}" + ".txt", Id);
StreamWriter file = new StreamWriter(arqNome);
file.WriteLine("ID: " + Id);
file.WriteLine("DOB: " + dOB);
file.WriteLine("Name: " + name);
file.WriteLine("Age: " + age);
file.Flush();
file.Close();
}
Class Client
public override void SaveData()
{
base.SaveData();
string arqName = string.Format("Person{0}" + ".txt", Id);
StreamWriter file = new StreamWriter(arqNome);
file.WriteLine("Cod: " + cod);
file.WriteLine("Credits: " + credits);
file.Flush();
file.Close();
}
The override method in Client is indeed override others data as Name, Age, DOB... I need to mantains both in same file.
StreamWriter is stream decorator, so you better instantiate FileStream and pass it to the StreamWriter constructor. Thus you can customize it. Append mode opens file and moves pointer to the end of file, so the next thing you write will be appended. And use using directive insted of explicitly calling Close():
Person class SaveData():
using (var fileStream = new FileStream(String.Format("Person{0}.txt", Id), FileMode.OpenOrCreate))
using (var streamWriter = new StreamWriter(fileStream))
{
streamWriter.WriteLine("ID: " + Id);
streamWriter.WriteLine("DOB: " + dOB);
streamWriter.WriteLine("Name: " + name);
streamWriter.WriteLine("Age: " + age);
}
Client class SaveData():
base.SaveData();
using (var fileStream = new FileStream(String.Format("Person{0}.txt", Id), FileMode.Append))
using (var streamWriter = new StreamWriter(fileStream))
{
streamWriter.WriteLine("Cod: " + cod);
streamWriter.WriteLine("Credits: " + credits);
}
You should split it into 2 methods: SaveData() and WriteData(StreamWriter file). SaveData creates the stream and then calls WriteData. Then you override only the WriteDate method, calling the base.
AlexDev's answer is correct. But if you can't alter Person code (and given that you store data per file) you can use 'append' flag to add data into existed file.
But it's not the best idea:
StreamWriter file = new StreamWriter(arqNome, append: true);

Not able to write a Text on txt File using C#

I have tried to write a string on text file,but its not writing anything and there is no exceptions. My code is:
public void CreateLog(string sLogInfo)
{
string sDestionation = null;
string sFileName = DateTime.Now.ToString("yyyyMMdd") + "_log.txt";
sDestionation = #"D:\Log\";
//sDestionation = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + ConfigurationManager.AppSettings["DestinationPath"].ToString();
string sFile = sDestionation + sFileName;
if (!System.IO.Directory.Exists(sDestionation))
{
System.IO.Directory.CreateDirectory(sDestionation);
}
StreamWriter oWriter = null;
if (!System.IO.File.Exists(sFile))
{
oWriter = File.CreateText(sFile);
}
else
{
oWriter = File.AppendText(sFile);
}
oWriter.WriteLine(DateTime.Now.ToString() + ": " + sLogInfo.Trim());
}
StreamWriter is IDisposable object. You should dispose it after using. For this you can use using statement like this:
public void CreateLog(string sLogInfo)
{
string sDestionation = null;
string sFileName = DateTime.Now.ToString("yyyyMMdd") + "_log.txt";
sDestionation = #"D:\Log\";
var sFile = sDestionation + sFileName;
if (!Directory.Exists(sDestionation))
{
Directory.CreateDirectory(sDestionation);
}
using (var oWriter = new StreamWriter(sFile, true))
oWriter.WriteLine(DateTime.Now + ": " + sLogInfo.Trim());
}
Use File.AppendAllText that will do all the steps (except creating folder) for you.
Otherwise you should properly dispose writer when you are done, preferably with using in the same function:
using(oWriter)
{
oWriter.WriteLine(DateTime.Now.ToString() + ": " + sLogInfo.Trim());
}
Your code looks fine, however, I think you should add at the end of it the following:
oWriter.Close()
You should flush (disposing is enough) your data into the file at the end of your code:
oWriter.Flush(); //Save (Clears all buffers for the current writer and causes any buffered data to be written to the underlying stream.)
oWriter.Dispose(); //Then free this resource
As Yuval mentioned looking at C#'s StreamWriter.cs class it does indeed calls the Flush method internally. See here: Reference

Why do I have an IOException in this case?

I'm programming a video player in C# (the video works fine) and what I need now is to get the libvlc logs as well as my custom logs to print them in a file.
I use NLog which handles the libvlc logs (with nVLC) and I raise an event for my custom logs, and in buth cases this function is called :
private static void tracerlogs(string erreur, VLCControl.ControleUtilisateurVLC.LogLevels LvLog)
{
string path = "logs.txt";//Sera redéfini dans l'appli
if (!File.Exists(path))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine(erreur + " " + LvLog.ToString());
sw.Close();
}
}
else
{
using (StreamWriter sw = File.AppendText(path))
{
sw.WriteLine(erreur + " " + LvLog.ToString());
sw.Close();
}
}
Console.WriteLine(erreur + " " + LvLog.ToString());
}
The problem is that I'm getting at random times a System.IO.IOException telling that "the process cannot access the file because it is being used by another process". Although I do close my StreamWriter (which should normally not be useful in a using block)... This makes my app crash. Does anyone have any idea why it does this ?
I finally solved it by adding a resource : as there was a conflict between different threads trying to access this function, I wrapped this :
private static void tracerlogs(string erreur, VLCControl.ControleUtilisateurVLC.LogLevels LvLog)
{
lock (LockLog) {
string path = "logs.txt";//Sera redéfini dans l'appli
if (!File.Exists(path))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine(erreur + " " + LvLog.ToString());
sw.Close();
}
}
else
{
using (StreamWriter sw = File.AppendText(path))
{
sw.WriteLine(erreur + " " + LvLog.ToString());
sw.Close();
}
}
Console.WriteLine(erreur + " " + LvLog.ToString());
}
}
And I declare a public static readonly object LockLog = new Object(); in my class. This works just fine ! Thanks to those who told me that this had to see with threading.

How to write log file in c#?

How would I write a log file in c#?
Currently i have a timer with this statement which ticks every 20 secs:
File.WriteAllText(filePath+"log.txt", log);
For everything that i want logged i do this:
log += "stringToBeLogged";
As you can assume the string log just grows and grows as the program runs. (I don't even know if there is a maximum chars per string?)
I assume that there must be better ways of doing this. i just thought that it would be heavy to write the whole file again and again for every time something is added to the log.
From the performance point of view your solution is not optimal. Every time you add another log entry with +=, the whole string is copied to another place in memory. I would recommend using StringBuilder instead:
StringBuilder sb = new StringBuilder();
...
sb.Append("log something");
...
// flush every 20 seconds as you do it
File.AppendAllText(filePath+"log.txt", sb.ToString());
sb.Clear();
By the way your timer event is probably executed on another thread. So you may want to use a mutex when accessing your sb object.
Another thing to consider is what happens to the log entries that were added within the last 20 seconds of the execution. You probably want to flush your string to the file right before the app exits.
create a class create a object globally and call this
using System.IO;
using System.Reflection;
public class LogWriter
{
private string m_exePath = string.Empty;
public LogWriter(string logMessage)
{
LogWrite(logMessage);
}
public void LogWrite(string logMessage)
{
m_exePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
try
{
using (StreamWriter w = File.AppendText(m_exePath + "\\" + "log.txt"))
{
Log(logMessage, w);
}
}
catch (Exception ex)
{
}
}
public void Log(string logMessage, TextWriter txtWriter)
{
try
{
txtWriter.Write("\r\nLog Entry : ");
txtWriter.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(),
DateTime.Now.ToLongDateString());
txtWriter.WriteLine(" :");
txtWriter.WriteLine(" :{0}", logMessage);
txtWriter.WriteLine("-------------------------------");
}
catch (Exception ex)
{
}
}
}
Use File.AppendAllText instead:
File.AppendAllText(filePath + "log.txt", log);
public static void WriteLog(string strLog)
{
StreamWriter log;
FileStream fileStream = null;
DirectoryInfo logDirInfo = null;
FileInfo logFileInfo;
string logFilePath = "C:\\Logs\\";
logFilePath = logFilePath + "Log-" + System.DateTime.Today.ToString("MM-dd-yyyy") + "." + "txt";
logFileInfo = new FileInfo(logFilePath);
logDirInfo = new DirectoryInfo(logFileInfo.DirectoryName);
if (!logDirInfo.Exists) logDirInfo.Create();
if (!logFileInfo.Exists)
{
fileStream = logFileInfo.Create();
}
else
{
fileStream = new FileStream(logFilePath, FileMode.Append);
}
log = new StreamWriter(fileStream);
log.WriteLine(strLog);
log.Close();
}
Refer Link:
blogspot.in
as posted by #randymohan, with using statements instead
public static void WriteLog(string strLog)
{
string logFilePath = #"C:\Logs\Log-" + System.DateTime.Today.ToString("MM-dd-yyyy") + "." + "txt";
FileInfo logFileInfo = new FileInfo(logFilePath);
DirectoryInfo logDirInfo = new DirectoryInfo(logFileInfo.DirectoryName);
if (!logDirInfo.Exists) logDirInfo.Create();
using (FileStream fileStream = new FileStream(logFilePath, FileMode.Append))
{
using (StreamWriter log = new StreamWriter(fileStream))
{
log.WriteLine(strLog);
}
}
}
Very convenient tool for logging is http://logging.apache.org/log4net/
You can also make something of themselves less (more) powerful. You can use http://msdn.microsoft.com/ru-ru/library/system.io.filestream (v = vs.110). Aspx
Add log to file with Static Class
public static class LogWriter
{
private static string m_exePath = string.Empty;
public static void LogWrite(string logMessage)
{
m_exePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
if (!File.Exists(m_exePath + "\\" + "log.txt"))
File.Create(m_exePath + "\\" + "log.txt");
try
{
using (StreamWriter w = File.AppendText(m_exePath + "\\" + "log.txt"))
AppendLog(logMessage, w);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private static void AppendLog(string logMessage, TextWriter txtWriter)
{
try
{
txtWriter.Write("\r\nLog Entry : ");
txtWriter.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(),DateTime.Now.ToLongDateString());
txtWriter.WriteLine(" :");
txtWriter.WriteLine(" :{0}", logMessage);
txtWriter.WriteLine("-------------------------------");
}
catch (Exception ex)
{
}
}
}
if(!File.Exists(filename)) //No File? Create
{
fs = File.Create(filename);
fs.Close();
}
if(File.ReadAllBytes().Length >= 100*1024*1024) // (100mB) File to big? Create new
{
string filenamebase = "myLogFile"; //Insert the base form of the log file, the same as the 1st filename without .log at the end
if(filename.contains("-")) //Check if older log contained -x
{
int lognumber = Int32.Parse(filename.substring(filename.lastIndexOf("-")+1, filename.Length-4); //Get old number, Can cause exception if the last digits aren't numbers
lognumber++; //Increment lognumber by 1
filename = filenamebase + "-" + lognumber + ".log"; //Override filename
}
else
{
filename = filenamebase + "-1.log"; //Override filename
}
fs = File.Create(filename);
fs.Close();
}
Refer link:
http://www.codeproject.com/Questions/163337/How-to-write-in-log-Files-in-C
This is add new string in the file
using (var file = new StreamWriter(filePath + "log.txt", true))
{
file.WriteLine(log);
file.Close();
}
There are 2 easy ways
StreamWriter - http://www.dotnetperls.com/streamwriter
Log4Net like Log4j(Java) - http://www.codeproject.com/Articles/140911/log4net-Tutorial
If your application is multithreaded then in some environments file.appendalltext could give error like file already in use and if you skip that then you could lose important logs .
For that you can use
Lock object technique with file.append.. in that case it will wait for existing process to close and the write your log
This can also save you from adding other libraries in your source
Above code will throw: Process can't access the file because it is being used by another process error because of File.Create(m_exePath + "\" + "log.txt"); if you will comment out this it will work as expected
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace SolutionLogWriter
{
public static class LogWriterClass
{
private static string m_exePath = string.Empty;
public static void LogWrite(string logMessage)
{
m_exePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string fullpath = m_exePath + "\\" + "log.txt";
if (File.Exists(fullpath))
{
File.Delete(fullpath);
}
// File.Create(fullpath);
try
{
FileStream fs = new FileStream(fullpath, FileMode.OpenOrCreate);
using (StreamWriter w = new StreamWriter(fs))
AppendLog(logMessage, w);
}
catch (Exception ex)
{
AppendLog(ex.ToString());
}
}
private static void AppendLog(string logMessage, TextWriter txtWriter=null)
{
try
{
txtWriter.Write("\r\nLog Entry : ");
txtWriter.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(), DateTime.Now.ToLongDateString());
txtWriter.WriteLine(" :");
txtWriter.WriteLine(" :{0}", logMessage);
txtWriter.WriteLine("-------------------------------");
}
catch (Exception ex)
{
txtWriter.Write(ex.Message);
}
}
}
}

How to write data to a text file without overwriting the current data

I can't seem to figure out how to write data to a file without overwriting it. I know I can use File.appendtext but I am not sure how to plug that into my syntax. Here is my code:
TextWriter tsw = new StreamWriter(#"C:\Hello.txt");
//Writing text to the file.
tsw.WriteLine("Hello");
//Close the file.
tsw.Close();
I want it to write Hello every time I run the program, not overwrite the previous text file. Thanks for reading this.
Pass true as the append parameter of the constructor:
TextWriter tsw = new StreamWriter(#"C:\Hello.txt", true);
Change your constructor to pass true as the second argument.
TextWriter tsw = new StreamWriter(#"C:\Hello.txt", true);
You have to open as new StreamWriter(filename, true) so that it appends to the file instead of overwriting.
Here's a chunk of code that will write values to a log file. If the file doesn't exist, it creates it, otherwise it just appends to the existing file. You need to add "using System.IO;" at the top of your code, if it's not already there.
string strLogText = "Some details you want to log.";
// Create a writer and open the file:
StreamWriter log;
if (!File.Exists("logfile.txt"))
{
log = new StreamWriter("logfile.txt");
}
else
{
log = File.AppendText("logfile.txt");
}
// Write to the file:
log.WriteLine(DateTime.Now);
log.WriteLine(strLogText);
log.WriteLine();
// Close the stream:
log.Close();
Best thing is
File.AppendAllText("c:\\file.txt","Your Text");
Look into the File class.
You can create a streamwriter with
StreamWriter sw = File.Create(....)
You can open an existing file with
File.Open(...)
You can append text easily with
File.AppendAllText(...);
First of all check if the filename already exists, If yes then create a file and close it at the same time then append your text using AppendAllText. For more info check the code below.
string FILE_NAME = "Log" + System.DateTime.Now.Ticks.ToString() + "." + "txt";
string str_Path = HostingEnvironment.ApplicationPhysicalPath + ("Log") + "\\" +FILE_NAME;
if (!File.Exists(str_Path))
{
File.Create(str_Path).Close();
File.AppendAllText(str_Path, jsonStream + Environment.NewLine);
}
else if (File.Exists(str_Path))
{
File.AppendAllText(str_Path, jsonStream + Environment.NewLine);
}
using (StreamWriter writer = File.AppendText(LoggingPath))
{
writer.WriteLine("Text");
}
none of the above did not work I found the solution myself
using (StreamWriter wri = File.AppendText("clients.txt"))
{
wri.WriteLine(eponimia_txt.Text + "," + epaggelma_txt.Text + "," + doy_txt.Text + "," + dieuthini_txt.Text + ","
+ proorismos_txt.Text + "," + poly_txt.Text + "," + sxePara_txt.Text + "," + afm_txt.Text + ","
+ toposFortosis_txt.Text + ",");
}

Categories

Resources