- The error only happens in production (not in debugging).
- The error only happens on the first application run after Windows login.
- The error occurs when we click BtnUseDesktop and thus fire the BtnUseDesktop_Click event (below).
- The Event Viewer stack starts with the The.Application.Name.Main() method…
- but our code does not have that method (it’s a WPF application).
Event Viewer
Application: The.Application.Name.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.IO.FileNotFoundException
Stack:
at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(
System.Object, System.Delegate, System.Object, Int32, System.Delegate)
at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(
System.Windows.Threading.DispatcherPriority, System.TimeSpan,
System.Delegate, System.Object, Int32)
at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr, Int32, IntPtr, IntPtr)
at MS.Win32.UnsafeNativeMethods.DispatchMessage(System.Windows.Interop.MSG ByRef)
at System.Windows.Threading.Dispatcher.PushFrameImpl(
System.Windows.Threading.DispatcherFrame)
at System.Windows.Threading.Dispatcher.PushFrame(
System.Windows.Threading.DispatcherFrame)
at System.Windows.Threading.Dispatcher.Run()
at System.Windows.Application.RunDispatcher(System.Object)
at System.Windows.Application.RunInternal(System.Windows.Window)
at System.Windows.Application.Run(System.Windows.Window)
at The.Application.Name.Main()
BtnUseDesktop_Click
private void BtnUseDesktop_Click(object sender, RoutedEventArgs e)
{
AvSwitcher switcher = new AvSwitcher();
this.RunAsyncTask(() =>
switcher.SwitchToDesktop(this.windowSyncSvc.ActiveLyncWindowHandle));
}
The AvSwitcher that the Click Event Calls Into
public class AvSwitcher
{
private DeviceLocationSvc deviceLocationSvc;
private UIAutomationSvc uiAutomationSvc;
private WindowMovingSvc windowMovingSvc;
private ManualResetEvent manualResetEvent;
private Modality audioVideo;
public static bool IsSwitching { get; set; }
public AvSwitcher()
{
this.deviceLocationSvc = new DeviceLocationSvc();
this.uiAutomationSvc = new UIAutomationSvc();
this.windowMovingSvc = new WindowMovingSvc();
}
public void SwitchToDesktop(IntPtr activeLyncConvWindowHandle)
{
this.BeginHold(DeviceLocation.Desktop, activeLyncConvWindowHandle);
}
public void SwitchToWall(IntPtr activeLyncConvWindowHandle)
{
this.BeginHold(DeviceLocation.Wall, activeLyncConvWindowHandle);
}
private Conversation GetLyncConversation()
{
Conversation conv = null;
if (LyncClient.GetClient() != null)
{
conv = LyncClient.GetClient().ConversationManager.Conversations.FirstOrDefault();
}
return conv;
}
private void BeginHold(DeviceLocation targetLocation, IntPtr activeLyncConvWindowHandle)
{
AvSwitcher.IsSwitching = true;
// make sure the class doesn't dispose of itself
this.manualResetEvent = new ManualResetEvent(false);
Conversation conv = this.GetLyncConversation();
if (conv != null)
{
this.audioVideo = conv.Modalities[ModalityTypes.AudioVideo];
ModalityState modalityState = this.audioVideo.State;
if (modalityState == ModalityState.Connected)
{
this.HoldCallAndThenDoTheSwitching(targetLocation, activeLyncConvWindowHandle);
}
else
{
this.DoTheSwitching(targetLocation, activeLyncConvWindowHandle);
}
}
}
private void HoldCallAndThenDoTheSwitching(
DeviceLocation targetLocation,
IntPtr activeLyncConvWindowHandle)
{
try
{
this.audioVideo.BeginHold(
this.BeginHold_callback,
new AsyncStateValues()
{
TargetLocation = targetLocation,
ActiveLyncConvWindowHandle = activeLyncConvWindowHandle
});
this.manualResetEvent.WaitOne();
}
catch (UnauthorizedAccessException)
{
// the call is already on hold
this.DoTheSwitching(targetLocation, activeLyncConvWindowHandle);
}
}
private void BeginHold_callback(IAsyncResult ar)
{
if (ar.IsCompleted)
{
DeviceLocation targetLocation = ((AsyncStateValues)ar.AsyncState).TargetLocation;
IntPtr activeLyncConvWindowHandle =
((AsyncStateValues)ar.AsyncState).ActiveLyncConvWindowHandle;
this.DoTheSwitching(targetLocation, activeLyncConvWindowHandle);
}
Thread.Sleep(2000); // is this necessary
this.audioVideo.BeginRetrieve(this.BeginRetrieve_callback, null);
}
private void DoTheSwitching(DeviceLocation targetLocation, IntPtr activeLyncConvWindowHandle)
{
DeviceLocationSvc.TargetDevices targetDevices =
this.deviceLocationSvc.GetTargetDevices(targetLocation);
this.SwitchScreenUsingWinApi(targetDevices.Screen, activeLyncConvWindowHandle);
this.SwitchVideoUsingLyncApi(targetDevices.VideoDevice);
this.SwitchAudioUsingUIAutomation(
targetDevices.MicName,
targetDevices.SpeakersName,
activeLyncConvWindowHandle);
AvSwitcher.IsSwitching = false;
}
private void SwitchScreenUsingWinApi(Screen targetScreen, IntPtr activeLyncConvWindowHandle)
{
if (activeLyncConvWindowHandle != IntPtr.Zero)
{
WindowPosition wp =
this.windowMovingSvc.GetTargetWindowPositionFromScreen(targetScreen);
this.windowMovingSvc.MoveTheWindowToTargetPosition(activeLyncConvWindowHandle, wp);
}
}
private void SwitchVideoUsingLyncApi(VideoDevice targetVideoDevice)
{
if (targetVideoDevice != null)
{
LyncClient.GetClient().DeviceManager.ActiveVideoDevice = targetVideoDevice;
}
}
private void SwitchAudioUsingUIAutomation(
string targetMicName,
string targetSpeakersName,
IntPtr activeLyncConvWindowHandle)
{
if (targetMicName != null && targetSpeakersName != null)
{
AutomationElement lyncConvWindow =
AutomationElement.FromHandle(activeLyncConvWindowHandle);
AutomationElement lyncOptionsWindow =
this.uiAutomationSvc.OpenTheLyncOptionsWindowFromTheConvWindow(lyncConvWindow);
this.uiAutomationSvc.SelectTheTargetMic(lyncOptionsWindow, targetMicName);
this.uiAutomationSvc.SelectTheTargetSpeakers(lyncOptionsWindow, targetSpeakersName);
this.uiAutomationSvc.InvokeOkayButton(lyncOptionsWindow);
}
}
private void BeginRetrieve_callback(IAsyncResult ar)
{
this.audioVideo.EndRetrieve(ar);
this.manualResetEvent.Set(); // allow the program to exit
}
private class AsyncStateValues
{
internal DeviceLocation TargetLocation { get; set; }
internal IntPtr ActiveLyncConvWindowHandle { get; set; }
}
}
One of the most commonly occurring errors in C#, FileNotFoundException
is raised when the developer tries to access a file in the program that either doesn’t exist or has been deleted. The following are some of the reasons the system is unable to locate the file:
- There might be a mismatch in the file name. For instance, instead of «demo.txt», the developer has written «Demo.txt».
- The file location may have changed.
- The file might have been deleted.
- The location or path the developer has passed might be wrong.
Syntax of FileNotFoundException
Similar to any class or a method, exceptions also have their own syntax.
Below is the syntax for FileNotFoundException:
public class FileNotFoundException :System.IO.IOException
The FileNotFoundException
comes under the class of IOExceptions, which is inherited from the SystemException.
SystemException
, which is inherited from the Exception
class, which is in turn inherited from the Object
class.
Object -> Exception -> SystemException -> IOException -> FileNotFoundException
An Example of FileNotFoundException
In the below code, System.IO
is imported, which is necessary for doing input and output operations on a file. Then within the main method, a try-catch block is placed to catch the exceptions, and within the try
block we have our StreamReader
class object.
The StreamReader
class is used to read text files. An object of StreamReader
, the path of file «demo.txt
» is passed. This file doesn’t exist in its constructor. Then the ReadToEnd
method is used to read the file till the end if it exists.
using System.IO;
using System;
class Program {
static void Main(string[] args) {
try {
using (StreamReader reader = new StreamReader("demo.txt")) {
reader.ReadToEnd();
}
} catch (FileNotFoundException e) {
Console.WriteLine(e.ToString());
}
}
}
An Output of FileNotFoundException Example
The output below is obtained on executing the above code. It includes a FileNotFoundException
along with its stack trace, which we can later use for debugging the exception.
System.IO.FileNotFoundException: Could not find file 'C:ConsoleApp1ConsoleApp1binDebugdemo.txt'.
File name: 'C:ConsoleApp1ConsoleApp1binDebugdemo.txt'
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
at System.IO.StreamReader..ctor(String path, Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize, Boolean checkHost)
at System.IO.StreamReader..ctor(String path)
at ConsoleApp1.Program.Main(String[] args) in C:ConsoleApp1ConsoleApp1Program.cs:line 17
It is essential to handle exceptions when working with files in any programming language.
How Does FileNotFoundException Work in C# ?
The FileNotFoundException class implements HRESULT COR_E_FILENOTFOUND
, which contains 0x80070002
value. When the code is executed and the file is not found by the system it creates a new instance of FileNotFoundException()
along with a string which contains a system defined message for the error.
Types of FileNotFoundException errors:
The Message property of FileNotFoundException
class gives the error message that explains the reason for the occurrence of the exception. This helps you to find out what kind of file not found error it is.
1. Could not find file error:
Let’s look at a block of code to observe this error. Instead of using StreamReader
, let’s directly use the method ReadAllText
of the File
class to read the text file.
using System.IO;
using System;
class Program {
static void Main(string[] args) {
try {
File.ReadAllText("demo.txt");
}
catch (FileNotFoundException e) {
Console.WriteLine(e.ToString());
}
}
}
Output: Could not find file error
In the following output the error message is of the format Could not find file 'filename'
. As discussed previously this happens because the developer is trying to load a file that doesn’t exist in the file system. The exception message gives a useful description of the error along with the absolute path to the missing file.
System.IO.FileNotFoundException: Could not find file 'C:ConsoleApp1ConsoleApp1binDebugdemo.txt'.
File name: 'C:ConsoleApp1ConsoleApp1binDebugdemo.txt'
2. Exception from HRESULT: 0x80070002
This error generally occurs when the developer tries to load a non-existing Assembly
into the system.
using System.IO;
using System;
using System.Reflection;
class Program {
static void Main(string[] args) {
try {
Assembly.LoadFile("C:\non_existing_dll_file.dll");
} catch (FileNotFoundException e) {
Console.WriteLine(e.ToString());
}
}
Output of Exception from HRESULT: 0x80070002
In this scenario as well the same FileNotFoundException
is raised but the error message is different. Unlike the previous output, the error message from System.Reflection
is quite hard to comprehend. Going through a stack trace can help pinpoint that the error is occurring during Assembly.LoadFile.
System.IO.FileNotFoundException: The system cannot find the file specified. (Exception from HRESULT: 0x80070002)
at System.Reflection.RuntimeAssembly.nLoadFile(String path, Evidence evidence)
at System.Reflection.Assembly.LoadFile(String path)
at ConsoleApp1.Program.Main(String[] args) in C:ConsoleApp1ConsoleApp1Program.cs:line 17
Another thing to keep in mind is that neither the filename nor the file path are provided in the message. This is because no name is printed in the output as the Filename
attribute on FileNotFoundException
is null.
How to debug FileNotFoundException
Let’s look at debugging the code, using the stack trace generated in the first example.
System.IO.FileNotFoundException: Could not find file 'C:ConsoleApp1ConsoleApp1binDebugdemo.txt'.
File name: 'C:ConsoleApp1ConsoleApp1binDebugdemo.txt'
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
at System.IO.StreamReader..ctor(String path, Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize, Boolean checkHost)
at System.IO.StreamReader..ctor(String path)
at ConsoleApp1.Program.Main(String[] args) in C:ConsoleApp1ConsoleApp1Program.cs:line 17
As we scan the stack trace from bottom to top, the StreamReader
object we have created to read the file to end with the path of the “demo.txt” file is creating an issue. This happens as the reader.ReadToEnd()
is trying to read the file which doesn’t exist. To resolve this create the file using a File
class method File.Create()
within the catch
block.
Code after debugging:
using System.IO;
using System;
class Program {
static void Main(string[] args) {
try {
using(StreamReader reader = new StreamReader("demo.txt")) {
reader.ReadToEnd();
}
} catch (FileNotFoundException e) {
Console.WriteLine("File doesn't exists so we created the file");
File.Create(e.FileName);
}
}
}
When the above code is executed we get the following output:
File doesn't exists so we created the file
How to Avoid FileNotFoundException in C#
Ultimately, it is better to avoid this exception rather than try to analyze or debug it, which could be time-consuming for extensive projects. You should use the File.Exists()
method to determine whether or not a file exists before referring to it. This method returns true
if the file exists, else it returns false
.
Example of File.Exists() method:
using System.IO;
using System;
class Program {
static void Main(string[] args) {
if (File.Exists("demos.txt")) {
using(StreamReader reader = new StreamReader("check.txt")) {
reader.ReadToEnd();
}
} else {
Console.WriteLine("File doesn't exist please create it");
}
}
}
An Output of File.Exists() method:
File doesn't exist please create it
Track, Analyze and Manage Errors With Rollbar
Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyse, and manage errors in real-time can help you proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing C# errors are easier than ever. Sign Up Today!
0 / 0 / 0 Регистрация: 03.04.2018 Сообщений: 15 |
|
1 |
|
03.04.2018, 17:22. Показов 21022. Ответов 15
С любым кодом при попытке работы с файлом выходит такая ошибка, файл есть, помогите пожалуйста) Миниатюры
0 |
mraklbrw 100 / 84 / 17 Регистрация: 01.04.2017 Сообщений: 780 |
||||
03.04.2018, 22:54 |
2 |
|||
Мб не по теме, но зачем 2 слеша используются везде? (а не только после диска) У меня работает так:
1 |
Администратор 15575 / 12548 / 4985 Регистрация: 17.03.2014 Сообщений: 25,474 Записей в блоге: 1 |
|
04.04.2018, 00:12 |
3 |
файл есть Выложи скриншот из Проводника где видно что файл есть. И так чтобы полный путь к папке был виден тоже.
1 |
0 / 0 / 0 Регистрация: 03.04.2018 Сообщений: 15 |
|
04.04.2018, 00:35 [ТС] |
4 |
вот Миниатюры
0 |
0 / 0 / 0 Регистрация: 03.04.2018 Сообщений: 15 |
|
04.04.2018, 00:38 [ТС] |
5 |
не умею кодить, а еще с файлами темболие, нужно вдохнуть жизни вот в такую форму
0 |
5863 / 4740 / 2940 Регистрация: 20.04.2015 Сообщений: 8,361 |
|
04.04.2018, 00:41 |
6 |
Сообщение было отмечено Usaga как решение РешениеКузьмаФ,
1 |
0 / 0 / 0 Регистрация: 03.04.2018 Сообщений: 15 |
|
04.04.2018, 00:52 [ТС] |
7 |
Файл реально называется trudovoi_dogovor.txt.txt. я поменял txt один теперь, всегда такая ошибка
0 |
263 / 224 / 108 Регистрация: 09.12.2015 Сообщений: 652 |
|
04.04.2018, 06:00 |
8 |
С любым кодом при попытке работы с файлом выходит такая ошибка, файл есть, помогите пожалуйста) Проблема может быть в том, что либо в имени самого файла на диске присутствуют символы кириллицы, либо Переименуйте сам файл и путь к нему. Для гарантии.
0 |
17203 / 12657 / 3321 Регистрация: 17.09.2011 Сообщений: 20,933 |
|
04.04.2018, 09:16 |
9 |
я поменял txt один теперь Вы приложили скриншот с файлом D:trudovoi_dogovor.txt и расширение изменили там же, а в коде открывается файл D:Отдел кадров техникумаtrudovoi_dogovor.txt — скриншот этой папки не был выложен. Есть ли там файл? Нормальное ли у него расширение?
0 |
0 / 0 / 0 Регистрация: 03.04.2018 Сообщений: 15 |
|
04.04.2018, 11:13 [ТС] |
10 |
Вы приложили скриншот с файлом D:trudovoi_dogovor.txt и расширение изменили там же, а в коде открывается файл D:Отдел кадров техникумаtrudovoi_dogovor.txt — скриншот этой папки не был выложен. Есть ли там файл? Нормальное ли у него расширение? расширение нужное вроде же Миниатюры
0 |
17203 / 12657 / 3321 Регистрация: 17.09.2011 Сообщений: 20,933 |
|
04.04.2018, 11:25 |
11 |
расширение нужное вроде же Еще разок, по-крупнее:
Вы приложили скриншот с файлом D:trudovoi_dogovor.txt и расширение изменили там же, а в коде открывается файл D:Отдел кадров техникумаtrudovoi_dogovor.txt — скриншот этой папки не был выложен.
0 |
0 / 0 / 0 Регистрация: 03.04.2018 Сообщений: 15 |
|
04.04.2018, 11:38 [ТС] |
12 |
Вы приложили скриншот с файлом D:trudovoi_dogovor.txt и расширение изменили там же, а в коде открывается файл я же поменял директорию, они совпадали
0 |
kolorotur 17203 / 12657 / 3321 Регистрация: 17.09.2011 Сообщений: 20,933 |
||||
04.04.2018, 11:41 |
13 |
|||
КузьмаФ, проверьте, как файл выглядит на самом деле:
У файла точно одно расширение?
0 |
0 / 0 / 0 Регистрация: 03.04.2018 Сообщений: 15 |
|
04.04.2018, 11:45 [ТС] |
14 |
У файла точно одно расширение? я и на других файлах пробовал
0 |
0 / 0 / 0 Регистрация: 03.04.2018 Сообщений: 15 |
|
04.04.2018, 12:11 [ТС] |
15 |
У файла точно одно расширение? Вот другое
0 |
0 / 0 / 0 Регистрация: 03.04.2018 Сообщений: 15 |
|
04.04.2018, 12:22 [ТС] |
16 |
ошибся, директории поправил в консоли заработатало Добавлено через 1 минуту Добавлено через 1 минуту
Сообщение от КузьмаФ ошибся, заработало в консоли
0 |
IT_Exp Эксперт 87844 / 49110 / 22898 Регистрация: 17.06.2006 Сообщений: 92,604 |
04.04.2018, 12:22 |
16 |
Hello @stephentoub ,
private static string Xml_Settings_Path = Directory.GetParent(Directory.GetCurrentDirectory()).FullName + @"/VSMP_Settings_File.xml";`
Still have same problem, i have changed path, i haved used Combine metod but always get error in redhat, System.IO.FileNotFoundException: Could not find file ‘/homeVSMP_Setting.xml’.
File name: ‘/homeVSMP_Setting.xml’
at Interop.ThrowExceptionForIoErrno(ErrorInfo errorInfo, String path, Boolean isDirectory, Func`2 errorRewriter) in //src/System.Private.CoreLib/shared/Interop/Unix/Interop.IOErrors.cs:line 24
at Microsoft.Win32.SafeHandles.SafeFileHandle.Open(String path, OpenFlags flags, Int32 mode) in //src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeFileHandle.Unix.cs:line 39
at System.IO.FileStream.OpenHandle(FileMode mode, FileShare share, FileOptions options) in //src/System.Private.CoreLib/shared/System/IO/FileStream.Unix.cs:line 61
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options) in //src/System.Private.CoreLib/shared/System/IO/FileStream.cs:line 237
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize) in //src/System.Private.CoreLib/shared/System/IO/FileStream.cs:line 179
at System.Xml.XmlDownloadManager.GetStream(Uri uri, ICredentials credentials, IWebProxy proxy, RequestCachePolicy cachePolicy) in //src/System.Private.Xml/src/System/Xml/XmlDownloadManager.cs:line 27
at System.Xml.XmlUrlResolver.GetEntity(Uri absoluteUri, String role, Type ofObjectToReturn) in //src/System.Private.Xml/src/System/Xml/XmlUrlResolver.cs:line 66
at System.Xml.XmlTextReaderImpl.OpenUrl() in //src/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImpl.cs:line 3087
at System.Xml.XmlTextReaderImpl.Read() in //src/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImpl.cs:line 1206
at System.Xml.XmlLoader.Load(XmlDocument doc, XmlReader reader, Boolean preserveWhitespace) in //src/System.Private.Xml/src/System/Xml/Dom/XmlLoader.cs:line 50
at System.Xml.XmlDocument.Load(XmlReader reader) in //src/System.Private.Xml/src/System/Xml/Dom/XmlDocument.cs:line 1336
at System.Xml.XmlDocument.Load(String filename) in //src/System.Private.Xml/src/System/Xml/Dom/XmlDocument.cs:line 1288
I create small Windows Forms progs in VisualStudio2010, just for hobby. After releasing them I use the .exe file to run them on other PCs, without having
to do any installation. Those PCs run Windows OS(7,vista,XP). The PC which I wrote the code had Win XP and the progs managed to work fine anytime.
Now I wrote another prog, on another PC, which runs Win 8.1 and I get the following error whenever I try to run the released .exe at other platforms, as mentioned above.
Problem signature: Problem Event Name: CLR20r3 Problem Signature 01: dmg_ors.exe Problem Signature 02: 1.0.0.0 Problem Signature 03: 52f4bad1 Problem Signature 04: DMG_ORS Problem Signature 05: 1.0.0.0 Problem Signature 06: 52f4bad1 Problem Signature 07: 3 Problem Signature 08: c Problem Signature 09: System.IO.FileNotFoundException OS Version: 6.1.7601.2.1.0.256.48 Locale ID: 1033 Additional Information 1: 82e2 Additional Information 2: 82e23b36efee975bd0e9417ff09fe7bb Additional Information 3: a1d6 Additional Information 4: a1d6e932d2c942475edff9f8fe05b46c Read our privacy statement online: http://go.microsoft.com/fwlink/?linkid=104288&clcid=0x0409 If the online privacy statement is not available, please read our privacy statement offline: C:Windowssystem32en-USerofflps.tx
How can I locate what file is missing?
tyvm
Jon Cage
36.1k36 gold badges135 silver badges213 bronze badges
asked Feb 7, 2014 at 11:50
1
Problem solved.I had to modify my main,IOT to catch that exception and see what was actually missing.
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.ThreadException += new
ThreadExceptionEventHandler(Application_ThreadException);
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
Application.Run(new Form1());
}
static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{
MessageBox.Show(e.Exception.Message, "Unhandled Thread Exception");
// here you can log the exception ...
}
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
MessageBox.Show((e.ExceptionObject as Exception).Message, "Unhandled UI Exception");
// here you can log the exception
}
Then I could see that the problem existed because Visual Basic Powerpack needed to be installed.I assume that machines without VS2010 installed,even if they have .NET 4.5, do not have that. The question is though, what was the difference this time and that package was needed IOT run the application….
The solution was found here actually, I need to say that.
http://www.csharp-examples.net/catching-unhandled-exceptions/
answered Feb 9, 2014 at 19:43
SteliosStelios
1611 silver badge4 bronze badges