I noticed that there are no line breaks in the file I'm creating using the code below. In the database, where I also store the text, those are present.
string story = "Critical error occurred after "
+ elapsed.ToString("hh:mm:ss")
+ "\n\n" + exception.Message;
File.WriteAllText(path, story);
So after some short googling I learned that I'm supposed to refer to the new lines using Environment-NewLine rather than the literal \n. So I added that as shown below.
string story = "Critical error occurred after "
+ elapsed.ToString("hh:mm:ss")
+ "\n\n" + exception.Message;
.Replace("\n", Environment.NewLine);
File.WriteAllText(path, story);
Still, no line breaks in the output file. What Am I missing?
Try StringBuilder methods - it's more readable and you don't need to remember about Environment.NewLine or \n\r or \n:
var sb = new StringBuilder();
string story = sb.Append("Critical error occurred after ")
.Append(elapsed.ToString("hh:mm:ss"))
.AppendLine()
.AppendLine()
.Append(exception.Message)
.ToString();
File.WriteAllText(path, story);
Simple solution:
string story = "Critical error occurred after "
+ elapsed.ToString("hh:mm:ss")
+ Environment.NewLine + exception.Message;
File.WriteAllLines(path, story.Split('\n'));
Instead of using
File.WriteAllText(path, content);
use
File.WriteAllLines(path, content.Split('\n'));
You can use WriteLine() method like below code
using (StreamWriter sw = StreamWriter(path))
{
string story = "Critical error occurred after " +elapsed.ToString("hh:mm:ss");
sw.WriteLine(story);
sw.WriteLine(exception.Message);
}
WriteAllText strips newlines, because it is not text.
Related
I'm having a really strange problem with an application I wrote a while back. It has worked without issues, but after leaving it alone for a while, it simply stopped functioning. I'll attach the code here:
try
{
using (Process proc = Process.Start(starter))
{
windowHider();
proc.WaitForExit();
DateTime endStamp = DateTime.Now;
endStamp = truncate(endStamp);
TimeSpan diff = endStamp.Subtract(startStamp);
string programSource = "applicationName";
string logLocation = "Application";
string occurance = "Var='" + varName + "' Var2='"+ var2Name + "' Var3='" + var3Name + "' Var4='" + var4Name + "' Var5='" + var5Name + "' Var6='" + var6Name + "'";
try
{
if (!EventLog.SourceExists(programSource))
{
EventLog.CreateEventSource(programSource, logLocation);
}
else
{
EventLog.WriteEntry(programSource, occurance);
}
}
catch (Exception err)
{
string message = "There was an error with usage logging. Please contact IT.";
MessageBox.Show(message);
errorLogger(message, err.ToString(), ((Control)sender).Name);
this.Close();
}
this.Close();
}
}
When the process that was started exits, the program writes to the application log. For some reason, however, I am getting the following error:
Exception: System.ComponentModel.Win32Exception (0x80004005): The
specified path is invalid
It cites this line as the cause:
EventLog.WriteEntry(programSource, occurance);
Any ideas as to what this sudden problem could be?
I figured it out! There was something corrupted in the registry, and there must have been another corrupted component lurking around somewhere. I changed the sourcename, and it worked without any issues.
The original sourcename works on other machines, which makes me think it was definitely just something wonky with the registry.
I would like to use gammu to send text messages with address and message, but I have a problem with the gammu parameters. If I start only the program it runs (string cmd1 = "c:\\G133\\bin\\gammu.exe ";). After adding parameters it gives this failure:
System.ComponentModel.Win32Exception' occurred in System.dll
Additional information: The system cannot find the file specified:
Code:
string[] sms = File.ReadAllLines(#"C:\\temp\\test.txt");
string address = sms[0];
string message = sms[1];
string cmd1 = #"C:\G133\bin\gammu.exe --sendsms TEXT" + " " +
"\"" + address + "\" -text " + " " + "\"" + message + "\"";
System.Diagnostics.Process.Start(cmd1);
Can anyone help me? Thanks in advance.
The output looks well:
Console.WriteLine(cmd1); - result
C:\G133\bin\gammu.exe --sendsms TEXT +12121234567 -text "Hello"
You need to call the overload of Start method which takes two parameters:
First one: the file to run;
Second one: the parameters
And it will looks like:
string app = #"path\to\your\target\app";
string prms = "your parameters";
System.Diagnostics.Process.Start(app, prms);
You should split the application and the arguments:
Process.Start(#"C:\G133\bin\gammu.exe", "--sendsms TEXT +12121234567 -text \"Hello\"");
I am currently working on a way to log into a text file an exception error of type System.InvalidOPerationException via a try{}... catch{} block. My concern is that Log.txt outputs:
Message :Exception of type 'System.Exception' was thrown.
StackTrace :
Date :4/21/2016 9:50:42 AM
Ideally I'd like it to be a bit more informative on the nature of the exception such those revealed by Microsoft Visual Studio dialog box. As an illustration:
An unhandled exception of type System.InvalidOPerationException occured
inSystem.dll
Additional information: the given ColumnName .... does not match up with
any column in datasource
see below the try....catch block applied on my method:
EDIT
try
{
// call method
}
catch (InvalidOperationException exc)
{
using (StreamWriter writer = new StreamWriter(logPath, true))
{
writer.WriteLine("Message :" + exc.Message + "<br/>" +
Environment.NewLine + "StackTrace :" + exc.StackTrace +
"" + Environment.NewLine + "Date :" +
DateTime.Now.ToString());
writer.WriteLine(Environment.NewLine + "-----------------------------------------------------------------------------"
+ Environment.NewLine);
}
}
Any relevant idea would be appreciated. Thanks in advance.
I have some code that is attempts to open a file on our network and what I am trying to do is put this into a try|catch block and I am running into a problem. When I try run my code I get an error: The name 'readProfile' does not exist in the current context (CS0103).
I know that since I am defining my streadreader object (readProfile) in the TRY of the try|catch block that I am not able to access the object but I don't know how to fix that. What I am trying to do is catch an error if I am unable to open the file (if someone else has it open, for example). Here is my code:
try {
StreamReader readProfile = new System.IO.StreamReader(ProDirectory.ToString() + #"\" + myProFile.ToString());
} catch (Exception ex) {
datalogger.Fatal(DateTime.Now.ToString() + ": Error while attempting to read file - " + ProDirectory.ToString() + #"\" + myProFile.ToString() + " The error is - " + ex.ToString());
}
If I remove the try|catch block, the code runs fine and does what I expect.
You can define variables outside the try, and then instantiate them inside:
StreamReader readProfile;
try
{
readProfile = new System.IO.StreamReader(ProDirectory.ToString() + #"\" + myProFile.ToString());
}
catch (Exception ex)
{
datalogger.Fatal(DateTime.Now.ToString() + ": Error while attempting to read file - " + ProDirectory.ToString() + #"\" + myProFile.ToString() + " The error is - " + ex.ToString());
// whatever you want to do with readProfile here. Of course, if the issue was that it couldn't create it, it still won't have been created...
}
Declare the StreamReader outside the try block but leave the assignment inside it.
I was trying to capture exception details with the below code, but it is not giving error in details.
I was trying to download a file from our ftp server with code like ftp classes. When file was not found, I fire the above method and pass in the exception. Unfortunately the method printed the following:
Error occured and Error details as follows
Exception occured in file
Exception occured in method SyncRequestCallback
Exception occured in line & column number 0 0
Here is my code. How can I capture the exception details (e.g. line number, method where the exception was thrown, etc.)?
public static string GetException(Exception ex)
{
//Get a StackTrace object for the exception
StackTrace st = new StackTrace(ex, true);
//Get the first stack frame
StackFrame frame = st.GetFrame(0);
//Get the file name
string fileName = frame.GetFileName();
//Get the method name
string methodName = frame.GetMethod().Name;
//Get the line number from the stack frame
int line = frame.GetFileLineNumber();
//Get the column number
int col = frame.GetFileColumnNumber();
string strBody = "Hi,<br/><br/>";
strBody = strBody + "Error occured and Error details as follows<br/>";
strBody = strBody + "Error message " + ex.Message + "<br/>";
strBody = strBody + "Exception occured in file " + fileName + "<br/>";
strBody = strBody + "Exception occured in method " + methodName + "<br/>";
strBody = strBody + "Exception occured in line & column number " + line + " " + col + "<br/><br/>Thanks";
return strBody;
}
Thanks
In order to capture more information you'll need to deploy .pdb files generated on build. This will allow you to know specific line where error happened.
As a side note, it seems to me that you're reinventing the wheel creating such a complex logic to log. There plenty of frameworks that will do the dirty job for you as log4net.
Calling ToString on an exception generally generates a readable version of the public details. And only the details available to the exception will be shown, so if the app is not running in debug mode and doesn't have corresponding *.pdb files (or you don't have them to attach, after the fact) - and symbols loads - then you can't get detailed source information.