I am making a program of which needs to output any errors that occur but in a timely fashion, it is a program for password recovery.
How can I change the exception text variable which is probably a string to only the actual exception minus all the unneeded stuff.
catch(Exception EX)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("AN ERROR OCCURED IN COPYING CHROMEPASSFILE: " + EX);
Console.ForegroundColor = ConsoleColor.Green;
}
Output:
AN ERROR OCCURED IN COPYING CHROMEPASSFILE: System.IO.IOException: The file 'C:\Users\Anonymous\Desktop\E_TEST\logindata.' already exists.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.File.InternalCopy(String sourceFileName, String destFileName, Boolean overwrite, Boolean checkHost)
at System.IO.File.Copy(String sourceFileName, String destFileName)
at Recover_All_Passwords.Program.Main(String[] args) in C:\Users\Anonymous\Documents\Visual Studio 2015\Projects\Recover_All_Passwords\Recover_All_Passwords\Program.cs:line 27
How can I output only that first line and none of those "At(s)"?
Just noticed the tag for exception says, I quote "An exception is a rarely occurring (exceptional!) condition that requires deviation from the program's normal flow."
Edit
Yes, the stacktrace is very helpful however I had only require the error message because the user will not be interested in anything but what had actually failed.
Rather than using EX, use the Message property on the Exception.
So your code becomes:
Console.WriteLine("AN ERROR OCCURED IN COPYING CHROMEPASSFILE: " + EX.Message);
For future reference, the "at(s)" are the StackTrace and are extremely useful for determining where your application is breaking..
Related
I'm developing an application for my company using C# and Xamarin.
I'm trying to testing my App to different devices but I have a problem:
My application works on my real Android phone, on Virtual Android, on Virtual Iphone but
It does not work on my real Iphone.
When I try, I get this error:
The "UnpackFrameworks" task failed unexpectedly.
System.IO.IOException: The file 'obj\iPhone\Debug\Frameworks\FirebaseFirestore.framework\FirebaseFirestore' already exists.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.File.InternalCopy(String sourceFileName, String destFileName, Boolean overwrite, Boolean checkHost)
at System.IO.FileInfo.CopyTo(String destFileName)
at Xamarin.iOS.Tasks.Windows.Zip.CopyDirectory(String source, String destination) in /Users/builder/azdo/_work/2/s/xamarin-macios/msbuild/Xamarin.iOS.Tasks.Windows/Zip.cs:line 31
at Xamarin.iOS.Tasks.Windows.Zip.Extract(String sourceFileName, String destinationPath) in /Users/builder/azdo/_work/2/s/xamarin-macios/msbuild/Xamarin.iOS.Tasks.Windows/Zip.cs:line 17
at Xamarin.iOS.HotRestart.Tasks.UnpackFrameworks.Execute() in /Users/builder/azdo/_work/2/s/xamarin-macios/msbuild/Xamarin.iOS.Tasks.Windows/Tasks/UnpackHotRestartFrameworks.cs:line 55
at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()
at Microsoft.Build.BackEnd.TaskBuilder.<ExecuteInstantiatedTask>d__26.MoveNext()
I'm using visual studio 2022 with C# and Xamarin.
I tried to delete obi and bin folders much times but nothing.
I also tried to apply this modify to Xamarin.iOS.HotRestart.targets file but when I try to use Firebase I get this error
Xamarin.PreBuilt.iOS[635:177579] System.TypeInitializationException: The type initializer for 'Plugin.CloudFirestore.FirestoreProvider' threw an exception. ---> System.ArgumentNullException: Value cannot be null.
Parameter name: firestore
at Plugin.CloudFirestore.FirestoreWrapper..ctor (Firebase.CloudFirestore.Firestore firestore) <0x104558138 + 0x0001a> in <xxxxxxxxxxxxxxxxxxxxx>:0
at Plugin.CloudFirestore.FirestoreProvider..cctor () <0x1039aa4c0 + 0x00014> in <xxxxxxxxxxxxxxxxxxxxx>:0
--- End of inner exception stack trace ---
at Plugin.CloudFirestore.CloudFirestoreImplementation.get_Instance () <0x1039a99b0 + 0x00000> in <xxxxxxxxxxxxxxxxxxxxx>:0
If I test an application without Firebase component, It works correctly.
Can someone help me?
So I decided to make a console application to automate some repetitive jobs that I generally do on a daily basis. The objective is to move some files to a network location as backup. The application runs fine when executed manually. But when scheduled, it throws an error. On examining the log file (to which all program output is mapped), I found the following stack trace and exception message:
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.File.InternalCopy(String sourceFileName, String destFileName, Boolean overwrite, Boolean checkHost)
at System.IO.File.Copy(String sourceFileName, String destFileName)
at automateDump.Program.Main(String[] args) in D:\software\automateDump\Program.cs:line 78
The user name or password is incorrect.
I'm using the File.Copy(src, dest) method in System.IO.
And for context, the file paths are:
Source: D:\u01\test.file. Destination: \\NetDrive\test.file
Any help would be appreciated.
EDIT 1
Code:
if (File.Exists(movePath + et1))
{
Console.WriteLine($"Copying {et1} to network location. Size - {sizeInMegaBytes(new FileInfo(movePath + et1).Length)}");
File.Copy(movePath + et1, networkPath + et1);
Console.WriteLine("Done Copying");
}
movePath and networkPath are source and destination paths, and et1 is the file.
sizeInMegaBytes() is a utility function that I wrote. It's irrelevant in this context.
EDIT 2
Exception Handling code:
catch (Exception ex)
{
using (logger = File.AppendText(#"D:\u01\logs.txt"))
{
logger.WriteLine($"{ex.StackTrace} \n {ex.Message}");
}
}
Theory: you have not checked the option to save the user password for the task:
Note the explanatory text: using a UNC path means you are trying to access a non-local resource!
If there is an exception in .NET code and and PDB file is available you normally get the errors with source code line numbers shown in the exception message. This seems to be different in command line executables, where I do not get any line number although a PDB file is available:
Anwendung: MNX.CommandLine.EpkFtpEventhandler.exe Frameworkversion: v4.0.30319 Beschreibung: Der Prozess wurde aufgrund eines Ausnahmefehlers beendet. Ausnahmeinformationen: System.Data.SqlClient.SqlException Stapel: bei System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(System.String, Boolean, Int32, Boolean) bei System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(System.Threading.Tasks.TaskCompletionSource`1, System.String, Boolean, Int32, Boolean) bei System.Data.SqlClient.SqlCommand.ExecuteNonQuery() bei MNX.DB.WriteLocal(System.String) bei MNX.DB.Write(System.String) bei MNX.CommandLine.EpkFtpEventHandler.Main(System.String[])
Does anyone know why?
Use Stack Frames and surround you code with a try catch:
try
{
throw new Exception();
}
catch (Exception ex)
{
// Get stack trace for the exception with source file information
var st = new StackTrace(ex, true);
// Get the top stack frame
var frame = st.GetFrame(0);
// Get the line number from the stack frame
var line = frame.GetFileLineNumber();
// Print the line number
Console.WriteLine($"An Error ({ex.Message}) occurred in line {line}");
}
To avoid plagiarism: I got the idea from this question.
I don't know why it isn't normally displayed in your console application though, but this should do it as well.
Try to empty symbol cache by accessing Debug > Options > Debugging > Symbols and clean your solution afterwards.
Exception.StackTrace gave back the line number, when it comes from a catch. Strangely only when I catch the exception, not when it's thrown without being catched.
We have a custom built web application built on ASP (2.0 it looks like) using C#. We recently moved it from an IIS6 environment to an IIS7. We have run into an issue where a page set up to view images that had been retrieved via a search is throwing an error. The code takes a copy of the image file and puts it into a work directory renaming the copy to the user's name.
bmpList[0].Save("c:\\inetpub\\wwwroot\\SiteName\\Work\\" + ((ImageUser)Session["ImageUser"]).Username + ".TIF", info, encParams);
I know that the wwwroot is no longer a valid directory in the path so I changed it to...
bmpList[0].Save("c:\\inetpub\\SiteName\\Work\\" + ((ImageUser)Session["ImageUser"]).Username + ".TIF", info, encParams);
Saved the file, did and IIS restart and cleared my browser cache and still receive an error...
A generic error occurred in GDI+.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Runtime.InteropServices.ExternalException: A generic error occurred in GDI+.
Source Error:
Line 180:
Line 181: //bmpList[0].Save("c:\\pi\\" + ((ImageUser)Session["ImageUser"]).Username + ".TIF", info, encParams);
Line 182: bmpList[0].Save("c:\\inetpub\\wwwroot\\SiteName\\Work\\" + ((ImageUser)Session["ImageUser"]).Username + ".TIF", info, encParams);
Line 183:
Line 184: for (int a = 1; a < numFiles; a++)
Source File: c:\inetpub\Sitename\SiteApp\View.aspx.cs Line: 182
Stack Trace:
[ExternalException (0x80004005): A generic error occurred in GDI+.]
System.Drawing.Image.Save(String filename, ImageCodecInfo encoder, EncoderParameters encoderParams) +615209
View.Page_PreRender(Object sender, EventArgs e) in c:\inetpub\SiteName\SiteApp\View.aspx.cs:182
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +25
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +42
System.Web.UI.Control.OnPreRender(EventArgs e) +11056766
System.Web.UI.Control.PreRenderRecursiveInternal() +108
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3394
It seems like a fairly straightforward thing but for some reason it is not updating (the path in the error remains exactly the same). What am I missing?
Almost all the time (i.e 99.9999% of the times), when using GDI, 'a generic error occured' means that the directory you are trying to save to doesn't have the proper permissions. Typically, you need to make sure that directory is allowing asp.net to modify files. Did you check the permission on the directory you are trying to save the files to?
So oddly enough the answer is actually as simple as it looks... almost.
Changing...
c:\inetpub\wwwroot\SiteName\Work\
to...
c:\inetpub\SiteName\Work\
worked. Why it was continuing to give me the same error from the browser after I changed the code on the .cs file was that the IP that they had bound to the site still belonged to a previous version of the machine so DNS was routing me over to that box instead. All said it ended up I was on the wrong OSI model layer. I only discovered it when I went to build a test version on the same box and went to unbind the IP from the broken site and bind it to my second test site and I found that the IP I wanted wasn't an option (so it must have been manually entered). Live and learn. Thanks for the input and advise.
I have a windowservice to import stuff to my system. Sometimes I get a "System.IO.IOException: The handle is invalid". Does anyone know why this exception occurs?
Below you can see the code thats triggers the exception:
foreach (string directoryPath in Directory.EnumerateDirectories(path))
{
// Import logic
}
My guess is that the underlying collection is changed during the execution, but I'm not sure of it.
Here is the stacktrace by the way:
System.IO.IOException: The handle is invalid.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileSystemEnumerableIterator`1.MoveNext()