如何:创建目录列表
下面的代码示例演示如何使用 I/O 类来创建目录中具有“.exe”扩展名的所有文件的列表。
示例
Imports System
Imports System.IO
Public Class DirectoryLister
Public Shared Sub Main(args() As String)
Dim path As String = Environment.CurrentDirectory
If args.Length > 0 Then
If Directory.Exists(args(0)) Then
path = args(0)
Else
Console.WriteLine("{0} not found; using current directory:",
args(0))
End If
End If
Dim dir As New DirectoryInfo(path)
For Each f As FileInfo In dir.GetFiles("*.exe")
Dim name As String = f.Name
Dim size As Long = f.Length
Dim creationTime As DateTime = f.CreationTime
Console.WriteLine("{0,-12:N0} {1,-20:g} {2}", size,
creationTime, name)
Next f
End Sub
End Class
using System;
using System.IO;
public class DirectoryLister
{
public static void Main(String[] args)
{
string path = Environment.CurrentDirectory;
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);
}
}
}
using namespace System;
using namespace System::IO;
public ref class DirectoryLister
{
public:
static void Main(array<String^>^ args)
{
String^ path = Environment::CurrentDirectory;
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 = gcnew DirectoryInfo(path);
for each (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);
}
}
};
int main()
{
DirectoryLister::Main(Environment::GetCommandLineArgs());
}
可靠编程
在本示例中,DirectoryInfo 是当前目录,用 (".") 表示,代码列出了当前目录中具有 .exe 扩展名的所有文件,同时还列出了这些文件的大小、创建时间和名称。 假设 C:\MyDir 的 \Bin 子目录中存在多个 .exe 文件,此代码的输出可能如下所示:
953 7/20/2000 10:42 AM C:\MyDir\Bin\paramatt.exe
664 7/27/2000 3:11 PM C:\MyDir\Bin\tst.exe
403 8/8/2000 10:25 AM C:\MyDir\Bin\dirlist.exe
如果需要另一个目录(如 C:\ 根目录)中的文件列表,请将参数“C:\”传入编译此代码生成的可执行文件,例如:“testApplication.exe C:\”。
注意 |
---|
Visual Basic 用户可以选择使用由 FileSystem 类提供的方法和属性执行文件 I/O 操作。 |