To determine whether a file exists prior to creating or performing an action on that file, you can use the static Exists method of the File class.
Determining whether a file exists is often critical to your code. If a file exists and you try to create it using one of the file creation methods, one of three things will happen: either the existing file will be overwritten; or, if the file is read-only, an exception will be thrown; or, an exception will be thrown indicating that the state of the filesystem is not what you think it is. There is a small window between the Exists call and the actions you take where another process could change the file system, so you should be prepared for that with proper exception handling.
The example of using static Exists as in the snippet code:
if (File.Exists(@"c:\test\test.txt"))
{
// Operate on that file here
}
Popularity: 1% [?]
RSS feed for comments on this post · TrackBack URI
Leave a reply