简体   繁体   中英

Reading From a Text File in C# before the file is actually selected

I'm writing a program which strongly depends on directories (it's a simple map generator for a game).

The thing is that before making a map you must choose a template which with you will work. This is done by getting a directories list in "Templates" directory, and converting them to an array which is later transported into ComboBox. Then, if in the folder we got a specific file, it is loaded, and values from it are placed into TextBoxes.

Let's say it: "Program\\Templates\\SelectedTemplate\\configfile.txt"

Sadly, because the list is empty by default, when I'm trying to compile the program, it gives me an "DirectoryNotFoundException", because he is looking for a directory that does not yet exist, like:

"Program\\Templates\\configfile.txt"

I tried to prevent it by selecting a default value which surely exist, and even by first checking if the file exist in the function. That does not help at all.

Any suggestions how to fix it? How to prevent "DirectoryNotFoundException" crashing app while it happens in the function that is not even yet loaded?

It's not clear what you're trying to do exactly. It makes no sense that the program generates the error when you compile it. I assume you meant when you run it.

It would also help if you post the relevant code block. How are you checking for the file existence? If the path to the file contains directory names that don't exist yet, it makes sense that exception will be thrown.

You can always wrap your code in a Try/Catch block, and test for that specific error, and this way your app won't crash.

Do a check on the directory and create it if it does not exist. Then Create a blank file as a place holder until later.

if (!File.Exists(@"Program\Templates\SelectedTemplate\"))
{
    Directory.CreateDirectory(@"Program\Templates\SelectedTemplate\");

    if (!File.Exists(@"Program\Templates\SelectedTemplate\configfile.txt"))
    {
        using (File.Create(@"Program\Templates\SelectedTemplate\configfile.txt")) ;
    }
}

Or something close to that should get rid of your error.

You could use Directory.Exists ("Program\\Templates\\SelectedTemplate\\") to check whether the directory exists and add some UI for the user to create that directory or even a new template inside.

Or if you just need it to fill your ComboBox, use try...catch when crating the array with the file names, catch the DirectoryNotFoundException and initialize your array with an empty one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM