?
Solved

create file and append it

Posted on 2010-11-11
7
Medium Priority
?
586 Views
Last Modified: 2012-05-10
I want to catch exceptions in a log file. I want to name my log file by date. If the file exists, it should append to it, if file does not exist, it should create one. I tried the following code but get error access to path is denied. I have shared the logs folder and given full control to every one. Please suggest what needs to be done.

I am getting the correct FileName as 11-11-2010.txt and Fullname (with path) as \\myserver\Projects\Results\Logs\11-11-2010.txt

Error: Access to the path '\\myserver\Projects\Results\Logs\11-11-2010.txt' is denied.

Thank You
public void WriteLog(string TextStr)
        {
            string FilePath = ConfigurationManager.AppSettings["LogPath"].ToString();
            
            //Set Filename By Date
            string FileName = DateTime.Now.ToString("MM-dd-yyyy") + ".txt";
            string FullName = FilePath + FileName;
            
            //if file does not exist, create one
            if (!File.Exists(FullName))
            {
                FileStream fileStream = new FileStream(@FullName, FileMode.Append);
            }

            StreamWriter SW;
            SW = File.AppendText(FullName);
            SW.WriteLine(TextStr);
            SW.Close();
        }

Open in new window

0
Comment
Question by:patd1
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 3
7 Comments
 
LVL 33

Accepted Solution

by:
Todd Gerbert earned 2000 total points
ID: 34115899
You're not closing the filestream, thus subsequent attempts to write to it will fail...try this, the "using" block will ensure that logWriter is displosed at the closing curly brace
public void WriteLog(string TextStr)
{
	string FilePath = ConfigurationManager.AppSettings["LogPath"].ToString();

	//Set Filename By Date
	string FileName = DateTime.Now.ToString("MM-dd-yyyy") + ".txt";
	string FullName = FilePath + FileName;

	//check if file exists, else create one
	using(StreamWriter logWriter = new StreamWriter(new FileStream(FullName, FileMode.Append, FileAccess.Write, FileShare.Read)))
	{
		logWriter.WriteLine(TextStr);
	}
}

Open in new window

0
 
LVL 36

Expert Comment

by:Miguel Oz
ID: 34115935
Your porlbem is that multiple threads or processes are trying to access your fiel at the same time.
You need to call your file using a lock or a mutex:
use lock if your program is multithreaded.
public void WriteLog(string TextStr)
        {
            string FilePath = ConfigurationManager.AppSettings["LogPath"].ToString();
           
            //Set Filename By Date
            string FileName = DateTime.Now.ToString("MM-dd-yyyy") + ".txt";
            string FullName = FilePath + FileName;
           
            //check if file exists, else create one
lock(this)
{
            FileStream fileStream = new FileStream(@FullName, FileMode.Append);
            StreamWriter SW;
            SW = File.AppendText(FullName);
            SW.WriteLine(TextStr);
            SW.Close();
}
        }


else use mutex
http://msdn.microsoft.com/en-us/library/system.threading.mutex.aspx

Alternatives: use Trace class and specify your file, log framework (log4net)
http://stackoverflow.com/questions/1260157/whats-the-most-widely-used-logging-framework-in-c

0
 

Author Comment

by:patd1
ID: 34115989
Another small problem though:
For the new line character I am adding "\\n" to the string, but it is simply writing \n to the file. what do I do to make it write a new line character?

Thanks
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
LVL 33

Expert Comment

by:Todd Gerbert
ID: 34116024
When you put two backslashes together it means "interpret this as a single backslash character, not an escape sequance"
So "\\n" = \n
and "\n" = newline
But, you probably want "\r\n" which is the normal line termination sequence in Windows, or you can use Environment.NewLine - e.g. WriteLine("Hello World!" + Environment.NewLine);
0
 

Author Comment

by:patd1
ID: 34116095
I tried both "\r\n" and Environment.NewLine
Both write \n in my text file
see example:
\nMain Method In ResultGenerator\nCaseNo not passed in.\nSystem.IndexOutOfRangeException: Index was outside the bounds of the array.
   at ResultGenerator.ResultGenerator.Main(String[] args) in E:\Projects\ResultGenerator\ResultGenerator.cs:line 20
0
 
LVL 33

Expert Comment

by:Todd Gerbert
ID: 34116136
If you start a string with "@" then no escape sequences are recognized.
e.g.
@"Hello\r\nWorld" = Hello\r\nWorld
"Hello\r\nWorld" = Hello <newline> World
I recommend you use the String.Format method,
string message = String.Format("{0}\r\n{1}\r\n{2}", "Main Method in ResultGen", "CaseNo not passed", ex.Message);
0
 

Author Comment

by:patd1
ID: 34117092
mas_oz2003:
Thanks for pointing me to alternate soultions for logging. Is it a good idea to write to OS event log?
Any disadvantages?
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Extention Methods in C# 3.0 by Ivo Stoykov C# 3.0 offers extension methods. They allow extending existing classes without changing the class's source code or relying on inheritance. These are static methods invoked as instance method. This…
Summary: Persistence is the capability of an application to store the state of objects and recover it when necessary. This article compares the two common types of serialization in aspects of data access, readability, and runtime cost. A ready-to…
This course is ideal for IT System Administrators working with VMware vSphere and its associated products in their company infrastructure. This course teaches you how to install and maintain this virtualization technology to store data, prevent vuln…
Do you want to know how to make a graph with Microsoft Access? First, create a query with the data for the chart. Then make a blank form and add a chart control. This video also shows how to change what data is displayed on the graph as well as form…

718 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question