How to Find Out If a File Exists in C#/.Net

How to find out if a file exists in C# / .NET?

Use:

File.Exists(path)

MSDN: http://msdn.microsoft.com/en-us/library/system.io.file.exists.aspx

Edit: In System.IO

How to check if a file exists in a folder?

This is a way to see if any XML-files exists in that folder, yes.

To check for specific files use File.Exists(path), which will return a boolean indicating wheter the file at path exists.

Is there a way to check if a file is in use?

Updated NOTE on this solution: Checking with FileAccess.ReadWrite will fail for Read-Only files so the solution has been modified to check with FileAccess.Read.

ORIGINAL:
I've used this code for the past several years, and I haven't had any issues with it.

Understand your hesitation about using exceptions, but you can't avoid them all of the time:

protected virtual bool IsFileLocked(FileInfo file)
{
try
{
using(FileStream stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.None))
{
stream.Close();
}
}
catch (IOException)
{
//the file is unavailable because it is:
//still being written to
//or being processed by another thread
//or does not exist (has already been processed)
return true;
}

//file is not locked
return false;
}

Determining if file exists using c# and resolving UNC path

You can create a FileInfo for an non-existing file. But then you can check the FileInfo.Exists property to determine whether the file exists, e.g:

FileInfo fi = new FileInfo(somePath);
bool exists = fi.Exists;

Update:
In a short test this also worked for UNC paths, e.g. like this:

FileInfo fi = new FileInfo(@"\\server\share\file.txt");
bool exists = fi.Exists;

Are you sure that the account (under which your application is running) has access to the share. I think that (by default) administrative rights are required to access the share "c$".

Check if a file exists on the server

the file path should be physical not virtual. Use

if (File.Exists(Server.MapPath(wordDocName)))

How to find out if a file exists in C# / .NET?

Use:

File.Exists(path)

MSDN: http://msdn.microsoft.com/en-us/library/system.io.file.exists.aspx

Edit: In System.IO



Related Topics



Leave a reply



Submit