sunjinbo
sunjinbo

Reputation: 2187

How to know whether the specified path refers to an existing file?

My current method is getting the top-level files in the current folder, and then check if has the file with the specified file name:

public async Task<bool> FileExists(StorageFolder folder, string fileName)
{
    IReadOnlyList<StorageFile> fileList = await folder.GetFilesAsync();
    StorageFile existFile = fileList.First(x => x.Name == fileName);
    return (existFile != null);
}

Is there have easily and efficiently way to do that?

Upvotes: 4

Views: 2256

Answers (4)

WonderWorker
WonderWorker

Reputation: 9062

For Windows Phone 8.1 RT, I recommend that you use try..catch, and do not equate an exception thrown to a boolean, as at this point it isn't known whether the file exists or not.

bool IsFileKnownToExist = false;

bool IsFileKnownToNotExist = false;

string FileName = "?";

try 
{
    await folder.GetFileAsync(FileName);

    IsFileKnownToExist = true;

} 
catch(Exception ex)
{
    //handle exception and set the booleans here. 
}

I will revisit this once I can get hold of a list of exceptions, and then will have a much improved way to equate to true or false.

However, there should be a third result returned to denote not knowing whether a file exists or not. In this case it would be worth setting up an enum:

public static enum Success
{
    True,
    False,
    Unsure
}

Then you may use the following code instead:

Success IsFileKnownToExist = Success.Unsure;

string FileName = "?";

try 
{
    await folder.GetFileAsync(FileName);

    IsFileKnownToExist = Success.True;

} 
catch(Exception ex)
{
    //handle exception and set the booleans here. 
}

switch(IsFileKnownToExist)
{
    case Success.True:
        //Code here when file exists
        break;

    case Success.False:
        //Code here when file does not exist
        break;

    default:
    case Success.Unsure:
        //Code here when it isn't known whether file exists or not
        break;
}

Upvotes: 1

WonderWorker
WonderWorker

Reputation: 9062

You'll need to acquaint yourself with the System.IO.File library.

string Directory = "C:\\Users\\" + Environment.UserName + "\\Desktop\\" + DateTime.Today.ToString("yyyy-MM-dd") + "-ExampleFolder";

if (!Directory.Exists(Directory)) 
{
    System.IO.Directory.CreateDirectory(Directory);

}  

string NameOfFile = "Example.txt";

string FilePath = System.IO.Path.Combine(Directory, NameOfFile);

if (System.IO.File.Exists(FilePath))
{
     //System.IO.File.Delete(FilePath);

}

Have a play with the above code.

Change the values of Directory and NameOfFile to see what happens.

Note: System.IO.File is part of .Net, which means the above code also works in Windows applications and websites.

Any questions, please ask.

Upvotes: 2

Romasz
Romasz

Reputation: 29792

You can think of getting file with its StorageFile.Path - but in this case you would have to look out for capabilities and remarks at MSDN link above - in case file doesn't exist it will throw an exception and you will have to catch it. It depends on your needs, number of files in folder and if you have to dive deep to your folder.

I would just use your method like this - as you except it to return boolean:

public async Task<bool> FileExists(StorageFolder folder, string fileName)
{
    return (await folder.GetFilesAsync()).Any(x => x.Name == fileName);
}

Of course the result will be very similar to yours.

You can easily extend this method to check for a group of files:

public async Task<bool[]> FilesExists(StorageFolder folder, IEnumerable<string> listFileNames)
{
    var files = await folder.GetFilesAsync();
    return listFileNames.Select(x => files.Any(y => y.Name == x)).ToArray();
}

The method refferns to Windows Runtime Apps, for Silverlight use File.Exists method like in this answer.

Upvotes: 2

BradStevenson
BradStevenson

Reputation: 1994

A simple way to check if a file exists is as such:

static async Task<bool> DoesFileExistAsync(StorageFolder folder, string filename) {
    try {
        await folder.GetFileAsync(filename);
        return true;
    } catch {
        return false;
    }
}

This works in WP8.1 Runtime.

Upvotes: 0

Related Questions