T.Brown
T.Brown

Reputation: 11

system io file not found exception/ error handling

I'm working in C# and I try to do a program that get some infoes the files in a Directory. I made it but i have a problem with the error Handling. When the program runs and for example I give just random numbers to list file infoes i get this error message:

"System.IO.DirectoryNotFoundException: "'Could not find a part of the path 'C:\Temp\first_project\first_project\bin\Debug\12345'.'"

Please someone help me to do the error handling.

Thank you in advance.

using System;
    using System.IO;
    class Test
        {
            static void Main(string[] args)
             {
                Console.WriteLine("Please :");
                string hely = Console.ReadLine();
                string[] __file = Directory.GetFiles(hely);
                string[] __dir = Directory.GetDirectories(hely);

                foreach (string i in __file)
                {
                    FileInfo fajl = new FileInfo(i);
                    Console.WriteLine("{0},{1},{2}", fajl.Name, fajl.Extension, fajl.LastWriteTime.ToString());
                }
                foreach (string i in __dir)
                {
                    DirectoryInfo _file = new DirectoryInfo(i);
                    Console.WriteLine("{0},{1},{2}", _file.Name, _file.Extension, _file.LastWriteTime.ToString());
                }


            Console.ReadKey();
             }

        }

Upvotes: 1

Views: 4112

Answers (4)

Stefan Steiger
Stefan Steiger

Reputation: 82136

You should check existence of a path with

System.IO.Directory.Exists(directory)

and of a file with

System.IO.File.Exists(filePath)

Then, you need to take the try-catch block inside the for-loop, to catch any possible exceptions that occur because of insufficient rights/permissions.

e.g.

foreach (string i in __file)
{
    try
    {
        FileInfo fajl = new FileInfo(i);
        Console.WriteLine("{0},{1},{2}", fajl.Name, fajl.Extension, fajl.LastWriteTime.ToString());
    }
    catch (System.Exception ex)
    {
        System.Console.WriteLine(ex.Message);
        throw;
    }

}

You could also create two try-catch blocks - depends on what you want to do.

try
{
    foreach (string i in __file)
    {
        try
        {
            FileInfo fajl = new FileInfo(i);
            Console.WriteLine("{0},{1},{2}", fajl.Name, fajl.Extension, fajl.LastWriteTime.ToString());
        }
        catch (System.Exception ex)
        {
            System.Console.WriteLine(ex.Message);
            throw;
        }

    }
}
catch (System.Exception exLoop)
{
    System.Console.WriteLine(exLoop.Message);
    throw;
}

Note that in your example, you should first check if the directory "hely" exists:

if (!System.IO.Directory.Exists(hely))
{
    System.Console.Error.WriteLine("Directory \"{0}\" does not exist.", hely);
    System.Environment.Exit(1);
    // or: return;
}

Since exception handling is usually very slow, I would however recommend that you check for the existence of the file/directory explicitly. It would also be a good idea to do so for the file/directory-listing & read-access rights for the respective user. But even if you do so, keep the try-catch, because there might be cases where your program suddenly fails - e.g. when a removable storage is forcefully removed.

Upvotes: 1

Harald Coppoolse
Harald Coppoolse

Reputation: 30454

RTFM?

Read Directory.GetFiles method

It says that you will get the DirectoryNotfound exception if the specified path is not found. Obviously folder 'C:\Temp\first_project\first_project\bin\Debug\12345' does not exist.

Proper code would be:

string hely = ...
try
{
    string[] files = Directory.GetFiles(hely);
    ProcessFiles(files);
}
catch (DirectoryNotFoundException exc)
{
    Console.WriteLine(exc.Message);
}

If you don't know how to react on exceptions read MSDN about exception handling

Upvotes: 0

Guy
Guy

Reputation: 50809

You can check if the file exists

foreach (string i in __file)
{
    if (File.Exists(i))
    {
        FileInfo fajl = new FileInfo(i);
        Console.WriteLine("{0},{1},{2}", fajl.Name, fajl.Extension, fajl.LastWriteTime.ToString());
    }
}

Upvotes: 0

Romano Zumbé
Romano Zumbé

Reputation: 8079

Use try catch

using System;
    using System.IO;
    class Test
        {
            static void Main(string[] args)
             {
                Console.WriteLine("Please :");
                string hely = Console.ReadLine();

                try
                {
                   string[] __file = Directory.GetFiles(hely);
                   string[] __dir = Directory.GetDirectories(hely);
                   foreach (string i in __file)
                   {
                      FileInfo fajl = new FileInfo(i);
                       Console.WriteLine("{0},{1},{2}", fajl.Name, fajl.Extension, fajl.LastWriteTime.ToString());
                   }

                   foreach (string i in __dir)
                   {
                      DirectoryInfo _file = new DirectoryInfo(i);
                      Console.WriteLine("{0},{1},{2}", _file.Name, _file.Extension, _file.LastWriteTime.ToString());
                   }
                }
                catch(System.IO.DirectoryNotFoundException ex)
                {
                    Console.WriteLine("Directory not found");
                }

                Console.ReadKey();
             }

        }

Upvotes: 0

Related Questions