Ошибка system io filenotfoundexception

  • 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 FileNotFoundExceptionis 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!

This is the third part in the series named Debugging common .NET exceptions. Today, I want to help you track down and fix a very common and very well-known exception, System.IO.FileNotFoundException. Admitted! In all instances this error is caused by trying to access a file that isn’t there. But, there are actually multiple scenarios that can trigger this exception. You may think you know everything there is to know about this exception, but I bet there is something left for you to learn. At least I did while digging down into the details for this post. Stay tuned to get the full story.

Debugging System.IO.FileNotFoundException - Cause and fix

Types of file not found errors

Let’s dig into the different causes of this error. The Message property on FileNotFoundException gives a hint about what is going on.

Could not find file ‘filename’

As the message says, you are trying to load a file that couldn’t be found. This type of error can be re-created using a single line of code:

try
{
    File.ReadAllText("non-existing.file");
}
catch (FileNotFoundException e)
{
    Console.WriteLine(e.ToString());
}

line 3 is the important one here. I’m trying to load a file that doesn’t exist on the file system (non-existing.file). In the example above, the program will print output to the console looking similar to this:

System.IO.FileNotFoundException: Could not find file 'APP_PATHbinDebugnon-existing.file'.
File name: 'APP_PATHbinDebugnon-existing.file'
   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.File.InternalReadAllText(String path, Encoding encoding, Boolean checkHost)
   at System.IO.File.ReadAllText(String path)
   at ConsoleApp.Program.Main(String[] args) in APP_PATHProgram.cs:line 19

APP_PATH will be the absolute path to the file that cannot be found. This type of FileNotFoundException actually contains all the information needed to debug the problem. The exception message contains a nice error description, as well as an absolute path to the missing file. If you want to present the user with the path or maybe create the file when not found, there is a nifty property available on FileNotFoundException:

catch (FileNotFoundException e)
{
    File.Create(e.FileName);
}

In the example I simply create the missing file by using the Filename property. I’ve seen code parsing the exception message to get the name of the missing file, which is kind of a downer when the absolute path is available right there on the exception :)

The system cannot find the file specified. (Exception from HRESULT: 0x80070002)

This error is typically thrown when trying to load an assembly that doesn’t exist. The error can be re-created like this:

try
{
    Assembly.LoadFile("c:\Nonexisting.dll");
}
catch (FileNotFoundException e)
{
    Console.WriteLine(e.ToString());
}

In this scenario, the program still throws a FileNotFoundException. But the exception message is different:

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 ConsoleApp.Program.Main(String[] args) in APP_PATHProgram.cs:line 20

Unlike the error thrown on reading the missing file, messages from the System.Reflection namespace are harder to understand. To find the cause of this error you will need to look through the stack trace, which hints that this is during Assembly.LoadFile. Notice that no filename is present in the exception message and in this case, the Filename property on FileNotFoundException is null.

Could not load file or assembly ‘assembly’ or one of its dependencies. The system cannot find the file specified.

An error similar to the one above is the Could not load file or assembly 'assembly' or one of its dependencies. The system cannot find the file specified. error. This also means that the program is trying to load an assembly that could not be found. The error can be re-created by creating a program that uses another assembly. Build the program, remove the references assembly (the .dll file) from the binDebug folder and run the program. In this case, the program fails during startup:

Unhandled Exception: System.IO.FileNotFoundException: Could not load file or assembly 'Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
   at ConsoleApp.Program.Main(String[] args)

In this example, I’m referencing an assembly named Lib, which doesn’t exist on the disk or in the Global Assembly Cache (GAC).

The typical cause of this error is that the referenced assembly isn’t on the file system. There can be multiple causes of this. To help you debug this, here are some things to check:

  1. If you are deploying using a system like Azure DevOps or Octopus Deploy, make sure all the files from the build output are copied to the destination.
  2. Right-click the referenced assembly in Visual Studio, click Properties and make sure that Copy Local is set to true:

Set Copy Local to True

Access errors when running on IIS

Until now all instances of this error have been a missing file from the disk. I want to round off this post with a quick comment about security. In some cases, the FileNotFoundException can be caused by the user account trying to access the file, and simply don’t have the necessary access. Under optimal circumstances, the framework should throw a System.UnauthorizedAccessException when this happens. But I have seen the issue in the past when hosting websites on IIS. Make sure that the ASP.NET worker process account (or NETWORK SERVICE depending on which user you are using) has access to all files and folders needed to run the application.

To make sure that the app pool user has access:

  1. Right-click the folder containing your web application
  2. Click Properties
  3. Select the Security tab
  4. Click Edit…
  5. Click Add…
  6. Input IIS AppPoolDefaultAppPool in the text area
  7. Click Check Names and verify that the user is resolved
  8. Click OK
  9. Assign Full control to the new user and save

Assign Full control for the new user

Also make sure to read the other posts in this series: Debugging common .NET exception.

elmah.io: Error logging and Uptime Monitoring for your web apps

This blog post is brought to you by elmah.io. elmah.io is error logging, uptime monitoring, deployment tracking, and service heartbeats for your .NET and JavaScript applications. Stop relying on your users to notify you when something is wrong or dig through hundreds of megabytes of log files spread across servers. With elmah.io, we store all of your log messages, notify you through popular channels like email, Slack, and Microsoft Teams, and help you fix errors fast.

elmah.io app banner

See how we can help you monitor your website for crashes
Monitor your website

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 FileNotFoundExceptionis 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!

This is the third part in the series named Debugging common .NET exceptions. Today, I want to help you track down and fix a very common and very well-known exception, System.IO.FileNotFoundException. Admitted! In all instances this error is caused by trying to access a file that isn’t there. But, there are actually multiple scenarios that can trigger this exception. You may think you know everything there is to know about this exception, but I bet there is something left for you to learn. At least I did while digging down into the details for this post. Stay tuned to get the full story.

Debugging System.IO.FileNotFoundException - Cause and fix

Types of file not found errors

Let’s dig into the different causes of this error. The Message property on FileNotFoundException gives a hint about what is going on.

Could not find file ‘filename’

As the message says, you are trying to load a file that couldn’t be found. This type of error can be re-created using a single line of code:

try
{
    File.ReadAllText("non-existing.file");
}
catch (FileNotFoundException e)
{
    Console.WriteLine(e.ToString());
}

line 3 is the important one here. I’m trying to load a file that doesn’t exist on the file system (non-existing.file). In the example above, the program will print output to the console looking similar to this:

System.IO.FileNotFoundException: Could not find file 'APP_PATHbinDebugnon-existing.file'.
File name: 'APP_PATHbinDebugnon-existing.file'
   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.File.InternalReadAllText(String path, Encoding encoding, Boolean checkHost)
   at System.IO.File.ReadAllText(String path)
   at ConsoleApp.Program.Main(String[] args) in APP_PATHProgram.cs:line 19

APP_PATH will be the absolute path to the file that cannot be found. This type of FileNotFoundException actually contains all the information needed to debug the problem. The exception message contains a nice error description, as well as an absolute path to the missing file. If you want to present the user with the path or maybe create the file when not found, there is a nifty property available on FileNotFoundException:

catch (FileNotFoundException e)
{
    File.Create(e.FileName);
}

In the example I simply create the missing file by using the Filename property. I’ve seen code parsing the exception message to get the name of the missing file, which is kind of a downer when the absolute path is available right there on the exception :)

The system cannot find the file specified. (Exception from HRESULT: 0x80070002)

This error is typically thrown when trying to load an assembly that doesn’t exist. The error can be re-created like this:

try
{
    Assembly.LoadFile("c:Nonexisting.dll");
}
catch (FileNotFoundException e)
{
    Console.WriteLine(e.ToString());
}

In this scenario, the program still throws a FileNotFoundException. But the exception message is different:

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 ConsoleApp.Program.Main(String[] args) in APP_PATHProgram.cs:line 20

Unlike the error thrown on reading the missing file, messages from the System.Reflection namespace are harder to understand. To find the cause of this error you will need to look through the stack trace, which hints that this is during Assembly.LoadFile. Notice that no filename is present in the exception message and in this case, the Filename property on FileNotFoundException is null.

Could not load file or assembly ‘assembly’ or one of its dependencies. The system cannot find the file specified.

An error similar to the one above is the Could not load file or assembly 'assembly' or one of its dependencies. The system cannot find the file specified. error. This also means that the program is trying to load an assembly that could not be found. The error can be re-created by creating a program that uses another assembly. Build the program, remove the references assembly (the .dll file) from the binDebug folder and run the program. In this case, the program fails during startup:

Unhandled Exception: System.IO.FileNotFoundException: Could not load file or assembly 'Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
   at ConsoleApp.Program.Main(String[] args)

In this example, I’m referencing an assembly named Lib, which doesn’t exist on the disk or in the Global Assembly Cache (GAC).

The typical cause of this error is that the referenced assembly isn’t on the file system. There can be multiple causes of this. To help you debug this, here are some things to check:

  1. If you are deploying using a system like Azure DevOps or Octopus Deploy, make sure all the files from the build output are copied to the destination.
  2. Right-click the referenced assembly in Visual Studio, click Properties and make sure that Copy Local is set to true:

Set Copy Local to True

Access errors when running on IIS

Until now all instances of this error have been a missing file from the disk. I want to round off this post with a quick comment about security. In some cases, the FileNotFoundException can be caused by the user account trying to access the file, and simply don’t have the necessary access. Under optimal circumstances, the framework should throw a System.UnauthorizedAccessException when this happens. But I have seen the issue in the past when hosting websites on IIS. Make sure that the ASP.NET worker process account (or NETWORK SERVICE depending on which user you are using) has access to all files and folders needed to run the application.

To make sure that the app pool user has access:

  1. Right-click the folder containing your web application
  2. Click Properties
  3. Select the Security tab
  4. Click Edit…
  5. Click Add…
  6. Input IIS AppPoolDefaultAppPool in the text area
  7. Click Check Names and verify that the user is resolved
  8. Click OK
  9. Assign Full control to the new user and save

Assign Full control for the new user

Also make sure to read the other posts in this series: Debugging common .NET exception.

elmah.io: Error logging and Uptime Monitoring for your web apps

This blog post is brought to you by elmah.io. elmah.io is error logging, uptime monitoring, deployment tracking, and service heartbeats for your .NET and JavaScript applications. Stop relying on your users to notify you when something is wrong or dig through hundreds of megabytes of log files spread across servers. With elmah.io, we store all of your log messages, notify you through popular channels like email, Slack, and Microsoft Teams, and help you fix errors fast.

elmah.io app banner

See how we can help you monitor your website for crashes
Monitor your website

  • 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; }
    }
}

Содержание

  1. Debugging System.IO.FileNotFoundException — Cause and fix
  2. Types of file not found errors
  3. Could not find file ‘filename’
  4. The system cannot find the file specified. (Exception from HRESULT: 0x80070002)
  5. Could not load file or assembly ‘assembly’ or one of its dependencies. The system cannot find the file specified.
  6. Access errors when running on IIS
  7. File Not Found Exception Class
  8. Definition
  9. Remarks
  10. Constructors
  11. Properties
  12. Methods
  13. Events
  14. File Not Found Exception Класс
  15. Определение
  16. Комментарии
  17. Конструкторы
  18. Свойства
  19. Методы
  20. События

Debugging System.IO.FileNotFoundException — Cause and fix

This is the third part in the series named Debugging common .NET exceptions. Today, I want to help you track down and fix a very common and very well-known exception, System.IO.FileNotFoundException. Admitted! In all instances this error is caused by trying to access a file that isn’t there. But, there are actually multiple scenarios that can trigger this exception. You may think you know everything there is to know about this exception, but I bet there is something left for you to learn. At least I did while digging down into the details for this post. Stay tuned to get the full story.

Types of file not found errors

Let’s dig into the different causes of this error. The Message property on FileNotFoundException gives a hint about what is going on.

Could not find file ‘filename’

As the message says, you are trying to load a file that couldn’t be found. This type of error can be re-created using a single line of code:

line 3 is the important one here. I’m trying to load a file that doesn’t exist on the file system ( non-existing.file ). In the example above, the program will print output to the console looking similar to this:

APP_PATH will be the absolute path to the file that cannot be found. This type of FileNotFoundException actually contains all the information needed to debug the problem. The exception message contains a nice error description, as well as an absolute path to the missing file. If you want to present the user with the path or maybe create the file when not found, there is a nifty property available on FileNotFoundException :

In the example I simply create the missing file by using the Filename property. I’ve seen code parsing the exception message to get the name of the missing file, which is kind of a downer when the absolute path is available right there on the exception 🙂

Would your users appreciate fewer errors?

The system cannot find the file specified. (Exception from HRESULT: 0x80070002)

This error is typically thrown when trying to load an assembly that doesn’t exist. The error can be re-created like this:

In this scenario, the program still throws a FileNotFoundException . But the exception message is different:

Unlike the error thrown on reading the missing file, messages from the System.Reflection namespace are harder to understand. To find the cause of this error you will need to look through the stack trace, which hints that this is during Assembly.LoadFile . Notice that no filename is present in the exception message and in this case, the Filename property on FileNotFoundException is null .

Could not load file or assembly ‘assembly’ or one of its dependencies. The system cannot find the file specified.

An error similar to the one above is the Could not load file or assembly ‘assembly’ or one of its dependencies. The system cannot find the file specified. error. This also means that the program is trying to load an assembly that could not be found. The error can be re-created by creating a program that uses another assembly. Build the program, remove the references assembly (the .dll file) from the binDebug folder and run the program. In this case, the program fails during startup:

In this example, I’m referencing an assembly named Lib, which doesn’t exist on the disk or in the Global Assembly Cache (GAC).

The typical cause of this error is that the referenced assembly isn’t on the file system. There can be multiple causes of this. To help you debug this, here are some things to check:

  1. If you are deploying using a system like Azure DevOps or Octopus Deploy, make sure all the files from the build output are copied to the destination.
  2. Right-click the referenced assembly in Visual Studio, click Properties and make sure that Copy Local is set to true :

Access errors when running on IIS

Until now all instances of this error have been a missing file from the disk. I want to round off this post with a quick comment about security. In some cases, the FileNotFoundException can be caused by the user account trying to access the file, and simply don’t have the necessary access. Under optimal circumstances, the framework should throw a System.UnauthorizedAccessException when this happens. But I have seen the issue in the past when hosting websites on IIS. Make sure that the ASP.NET worker process account (or NETWORK SERVICE depending on which user you are using) has access to all files and folders needed to run the application.

To make sure that the app pool user has access:

  1. Right-click the folder containing your web application
  2. Click Properties
  3. Select the Security tab
  4. Click Edit.
  5. Click Add.
  6. Input IIS AppPoolDefaultAppPool in the text area
  7. Click Check Names and verify that the user is resolved
  8. Click OK
  9. Assign Full control to the new user and save

Also make sure to read the other posts in this series: Debugging common .NET exception.

Источник

File Not Found Exception Class

Definition

Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.

The exception that is thrown when an attempt to access a file that does not exist on disk fails.

FileNotFoundException uses the HRESULT COR_E_FILENOTFOUND which has the value 0x80070002.

Constructors

Initializes a new instance of the FileNotFoundException class with its message string set to a system-supplied message.

Initializes a new instance of the FileNotFoundException class with the specified serialization and context information.

Initializes a new instance of the FileNotFoundException class with a specified error message.

Initializes a new instance of the FileNotFoundException class with a specified error message and a reference to the inner exception that is the cause of this exception.

Initializes a new instance of the FileNotFoundException class with a specified error message, and the file name that cannot be found.

Initializes a new instance of the FileNotFoundException class with a specified error message, the file name that cannot be found, and a reference to the inner exception that is the cause of this exception.

Properties

Gets a collection of key/value pairs that provide additional user-defined information about the exception.

(Inherited from Exception) FileName

Gets the name of the file that cannot be found.

Gets the log file that describes why loading of an assembly failed.

Gets or sets a link to the help file associated with this exception.

(Inherited from Exception) HResult

Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception.

(Inherited from Exception) InnerException

Gets the Exception instance that caused the current exception.

(Inherited from Exception) Message

Gets the error message that explains the reason for the exception.

Gets or sets the name of the application or the object that causes the error.

(Inherited from Exception) StackTrace

Gets a string representation of the immediate frames on the call stack.

(Inherited from Exception) TargetSite

Gets the method that throws the current exception.

(Inherited from Exception)

Methods

Determines whether the specified object is equal to the current object.

(Inherited from Object) GetBaseException()

When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions.

(Inherited from Exception) GetHashCode()

Serves as the default hash function.

(Inherited from Object) GetObjectData(SerializationInfo, StreamingContext)

Sets the SerializationInfo object with the file name and additional exception information.

When overridden in a derived class, sets the SerializationInfo with information about the exception.

(Inherited from Exception) GetType()

Gets the runtime type of the current instance.

(Inherited from Exception) MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object) ToString()

Returns the fully qualified name of this exception and possibly the error message, the name of the inner exception, and the stack trace.

Events

Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception.

Источник

File Not Found Exception Класс

Определение

Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.

Исключение, которое выдается при попытке получить доступ к файлу или каталогу, которых нет на диске.

Комментарии

FileNotFoundException использует COR_E_FILENOTFOUND HRESULT, имеющий значение 0x80070002.

Конструкторы

Инициализирует новый экземпляр класса FileNotFoundException строкой сообщений, настроенной на отображение предоставляемого системой сообщения.

Инициализирует новый экземпляр класса FileNotFoundException с указанными данными о сериализации и контексте.

Инициализирует новый экземпляр класса FileNotFoundException с указанным сообщением об ошибке.

Инициализирует новый экземпляр класса FileNotFoundException указанным сообщением об ошибке и ссылкой на внутреннее исключение, вызвавшее данное исключение.

Инициализирует новый экземпляр класса FileNotFoundException с заданным сообщением об ошибке и именем файла, который не удается найти.

Инициализирует новый экземпляр класса FileNotFoundException с заданным сообщением об ошибке, именем файла, который не удается найти, и ссылкой на внутреннее исключение, являющееся причиной данного исключения.

Свойства

Возвращает коллекцию пар «ключ-значение», предоставляющую дополнительные сведения об исключении.

(Унаследовано от Exception) FileName

Получает имя файла, который не удается найти.

Возвращает имя журнала, в котором описано, почему закончилась неудачей загрузка сборки.

Получает или задает ссылку на файл справки, связанный с этим исключением.

(Унаследовано от Exception) HResult

Возвращает или задает HRESULT — кодированное числовое значение, присвоенное определенному исключению.

(Унаследовано от Exception) InnerException

Возвращает экземпляр класса Exception, который вызвал текущее исключение.

(Унаследовано от Exception) Message

Возвращает сообщение об ошибке с объяснением причин исключения.

Возвращает или задает имя приложения или объекта, вызывавшего ошибку.

(Унаследовано от Exception) StackTrace

Получает строковое представление непосредственных кадров в стеке вызова.

(Унаследовано от Exception) TargetSite

Возвращает метод, создавший текущее исключение.

(Унаследовано от Exception)

Методы

Определяет, равен ли указанный объект текущему объекту.

(Унаследовано от Object) GetBaseException()

При переопределении в производном классе возвращает исключение Exception, которое является первопричиной одного или нескольких последующих исключений.

(Унаследовано от Exception) GetHashCode()

Служит хэш-функцией по умолчанию.

(Унаследовано от Object) GetObjectData(SerializationInfo, StreamingContext)

Устанавливает объект SerializationInfo с именем файла и дополнительными сведениями об исключении.

При переопределении в производном классе задает объект SerializationInfo со сведениями об исключении.

(Унаследовано от Exception) GetType()

Возвращает тип среды выполнения текущего экземпляра.

(Унаследовано от Exception) MemberwiseClone()

Создает неполную копию текущего объекта Object.

(Унаследовано от Object) ToString()

Возвращает полное имя данного исключения и, возможно, сообщение об ошибке, имя внутреннего исключения и трассировку стека.

События

Возникает, когда исключение сериализовано для создания объекта состояния исключения, содержащего сериализованные данные об исключении.

Источник

C# FileNotFoundException

Introduction to C# FileNotFoundException

While dealing with Files Input Output in C#, various exception might rise, but the FileNotFoundException is raised when we attempt to access a file in our program and that file does not exist or is deleted. So, basically, the FileNotFound Exception occurs when we have an address to a file in our system, but when we execute the program, the file we mentioned or passed, is not to be found. There could be multiple reasons for why this file is not found. The file maybe deleted from the location or the file name could have been changed and does not match with the names we mentioned. It is also possible when we pass a wrong address and when it hits the address, there is no file and thus the exception occurs.

Syntax:

Every method, class or exception has its standard syntax.

In case of FileNotFound Exception, the standard syntax is as follows:

public class FileNotFoundException :System.IO.IOException

The FileNotFound Exception is part of IOException, which is inherited from SystemException, going up to Exception and Object class.

How FileNotFoundException work in C#?

  • The FileNotFoundException implements the HRESULT COR_E_FILENOTFOUND, which holds the 0x80070002 value.
  • This FileNotFound Exception usually occurs when dealing with Input Output operations for files.
  • When the code does not find the file, it creates a new instance of FileNotFoundException() along with its message string, which is a system set message for the error.
  • In variety of such constructors, string can be added, context information and error message can be displayed.
  • Additionally, another constructor can provide reference to the inner exception that caused this exception.

Examples of C# FileNotFoundException

Given below are the examples mentioned:

Example #1

Code:

using System;
using System.IO;
class Program {
static void Main() {
try {
using (StreamReaderfilereader = new StreamReader("nofile.txt")) {
filereader.ReadToEnd();
}
}
catch (FileNotFoundException ex) {
Console.WriteLine(ex);
}
}
}

Explanation:

  • We have simply started with the system files. System.IO is an important import file here, as we will be doing operations over file Input and Output. Then we have our class and main method. We have already entered our try catch block in order to catch the exception. We then have our StreamReader class, which is found in system.IO namespace.
  • The StreamReader class is used to read a text file. It is easy to use and provides a good performance. With StreamReader, we have our object that calls the nofile.txt, which as we know does not exist. Then we have ReadToEnd method which will read the file until the end, if it is found. Finally, we have our catch block, which, of course, as we are speaking holds the FileNotFound Exception and when it catches it, it will be printed in output statement in the next line.
  • Upon successful execution of the above code, the output will be an exception, “Could not find file…”.

Output:

c# FileNotFoundException 1

Example #2

Here we will execute the code similar to above code, but without any try catch block, it will be simple program, where we cannot guess what exactly could go wrong.

Code:

using System.IO;
using System;
class Program {
static void Main() {
using (StreamReaderfilereader = new StreamReader("incorrectfilename.txt")) {
filereader.ReadToEnd();
}
}
}

Explanation:

  • With our second example, the code is almost similar to our first example, but we have specifically not implemented any way to catch the exception. Started with system file, then our class and main method. Then moving ahead to StreamReader, we have our file name passed, which is incorrect and in the next line we attempt to read the file to the end.
  • But we have not tried to catch or identify the exception here, this is a scenario where we believe that the file exist and so we don’t expect any exception. Upon executing, it will print Unhandled Exception and the “System.IO.FileNotFoundException: Could not find file” will be thrown.

Output:

c# FileNotFoundException 2

And as you can see, unlike our earlier example, this is an unhandled exception and output is as expected.

How to Avoid FileNotFoundException in C#?

Just like any other exception, this FileNotFound Exception can be avoided. Out of the ways that we can use to avoid this exception, File.Exists method is recommended. When we are uncertain if the file we are passing in argument is not available at the source link, it is better to use File.Exists method. File.Exists method is recommended.

Example:

We will use the File.Exists method in program and see how is can be used further.

Code:

using System.IO;
using System;
class Program {
static void Main() {
bool ifexists = File.Exists("incorrectfilename.txt");
Console.WriteLine("n "+ifexists);
}
}

Explanation:

  • Our code here is ideally in case if we are not sure of the existence of the file that we are about to use. This is simple implementation, we can have such code in loops where it checks for different or alternative files and whichever exists is selected for the operation.
  • We have File.Exists method, where we have passed the file name and are checking if the file exists.
  • Now in the next line, we have print statement, which will print a boolean value, either True or False, based on the existence of file. Our file does not exists, so it must return a false.

Output:

false

Conclusion

To Conclude, the FileNotFound Exception comes from IO system namespace of the object class. FileNotFoundException is responsible for occurring at times when we pass a file or are attempting to execute input or output operations with file but the file does not exists. Other reasons could be, incorrect file name, or incorrect source link. File Exists method can be used to avoid this exception.

Recommended Articles

This is a guide to C# FileNotFoundException. Here we discuss how FileNotFoundException work in C#,  how to avoid exception with programming examples. You may also have a look at the following articles to learn more –

  1. C# Serialization
  2. C# StringWriter
  3. C# Custom Attribute
  4. Regular Expression in C#

Hi Experts,

I am using command prompt to install a service on Windows Embedded XP. I try following command:

C:WindowsMicrosoft.NetFrameworkv2.0.50727installutil.exe «D:MyServicetestService.exe»

but I get bellow error. Seems I am missing some files not sure which one.

Error in Install.log file:

Running a transacted installation.

Beginning the Install phase of the installation.

An exception occurred during the Install phase.
System.IO.FileNotFoundException: Could not load file or assembly ‘System.Runtime.Serialization.Formatters.Soap, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a’ or one of its dependencies. The system cannot find the file specified.
The inner exception System.IO.FileNotFoundException was thrown with the following error message: The system cannot find the file specified. (Exception from HRESULT: 0x80070002).

The Rollback phase of the installation is beginning.
An exception occurred during the Rollback phase of the System.Configuration.Install.AssemblyInstaller installer.
System.IO.FileNotFoundException: Could not load file or assembly ‘System.Runtime.Serialization.Formatters.Soap, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a’ or one of its dependencies. The system cannot find the file specified.
The inner exception System.IO.FileNotFoundException was thrown with the following error message: The system cannot find the file specified. (Exception from HRESULT: 0x80070002).
An exception occurred during the Rollback phase of the installation. This exception will be ignored and the rollback will continue. However, the machine might not fully revert to its initial state after the rollback is complete.

The Rollback phase completed successfully.

The transacted install has completed.

Any clue?


Maverick

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

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

  • Ошибка sw rev check fail bootloader
  • Ошибка svs на лифан солано причины
  • Ошибка svs на лифан солано 620
  • Ошибка svs на лифан x60
  • Ошибка svs на лифан x50