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
What Is the Maximum Resolution of C# .Net Bitmap
How to Return an Anonymous Type from a Method
Mvvm: Binding Radio Buttons to a View Model
Get SQL Query from Linq to SQL
Overloading Getter and Setter Causes a Stack Overflow in C#
Why Can't I Assign a List<Derived> to a List<Base>
Windows 7 and Vista Uac - Programmatically Requesting Elevation in C#
How to Get the Last Five Characters of a String Using Substring() in C#
Gps Socket Communication (Concox)
Zooming Graphics Based on Current Mouse Position
How to Save Image in Database Using C#
Query Extremely Slow in Code But Fast in Ssms
How to Make the Value of a Variable Track the Value of Another
How Should Anonymous Types Be Used in C#