利用C#中的IO来查看文件是否存在

本篇将介绍如何使用C#中的IO Class来查看文件是否存在。

首先,在操作之前需要在程序中声明System.IO。

然后需要使用到File和Directory Class。

具体操作如下:

using System;
using System.IO;

namespace IO
{
class Program
{
static void Main(string[] args)
{
string path = ".";
if(args.Length>0)
{
if (Directory.Exists(args[0]))
{
path = args[0];
}
else
{
Console.WriteLine("{0} not found; using current directory:", args[0]);
}
}

DirectoryInfo dir = new DirectoryInfo(path);
foreach (FileInfo f in dir.GetFiles("*.exe"))
{
string name = f.Name;
long size = f.Length;
DateTime creationTime = f.CreationTime;
Console.WriteLine("{0, -12:N0} {1, -20:g} {2}", size, creationTime, name);
}

Console.ReadLine();
}
}
}

因为本程序是在当前目录运行,因此得到的结果也会是在当前的目录下所有的exe文件:

5,632        26/07/2015 8:59 p.m. IO.exe
23,168 26/07/2015 8:36 p.m. IO.vshost.exe

如果想要通过以上程序查看其它目录的exe文件,只需要运行以下:

IO.exe c:windows