C#中如何建立資料夾
阿新 • • 發佈:2019-01-06
C#中對資料夾操作需要用到Directory Class。其中提供了建立、刪除、移動、列舉等靜態方法。該類不能被繼承。
以下程式碼實現了建立資料夾。
?1 2 3 4 |
if
(!Directory.Exists(sPath))
{
Directory.CreateDirectory(sPath);
}
|
以下是MSDN上Directory Class的Sample code。
以下程式碼首先檢查指定的資料夾是否存在,若存在則刪除之,否則建立之。接下來移動資料夾,在其中建立檔案並統計資料夾中檔案數目。
?1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
using
System;
using
System.IO;
class
Test
{
public
static void
Main()
{
// Specify the directories you want to manipulate.
string
path = @"c:\MyDir" ;
string
target = @"c:\TestDir" ;
try
{
// Determine whether the directory exists.
if
(!Directory.Exists(path))
{
// Create the directory it does not exist. Directory.CreateDirectory(path);
}
if
(Directory.Exists(target))
{
// Delete the target to ensure it is not there.
Directory.Delete(target,
true );
}
// Move the directory.
Directory.Move(path, target);
// Create a file in the directory.
File.CreateText(target +
@"\myfile.txt" );
// Count the files in the target directory. Console.WriteLine( "The number of files in {0} is {1}" ,
target, Directory.GetFiles(target).Length);
}
catch
(Exception e)
{
Console.WriteLine( "The process failed: {0}" , e.ToString());
}
finally
{}
}
}
|
以下程式碼演示瞭如何計算資料夾大小。
?1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
// The following example calculates the size of a directory
// and its subdirectories, if any, and displays the total size
// in bytes.
using
System;
using
System.IO;
public
class ShowDirSize
{
public
static long
DirSize(DirectoryInfo d)
{
long
Size = 0;
// Add file sizes.
FileInfo[] fis = d.GetFiles();
foreach
(FileInfo fi in
fis)
{
Size += fi.Length;
}
// Add subdirectory sizes.
DirectoryInfo[] dis = d.GetDirectories();
foreach
(DirectoryInfo di in
dis)
{
Size += DirSize(di);
}
return (Size);
}
public
static void
Main( string [] args)
{
if
(args.Length != 1)
{
Console.WriteLine( "You must provide a directory argument at the command line." );
}
else
{
DirectoryInfo d =
new DirectoryInfo(args[0]);
long
dsize = DirSize(d);
Console.WriteLine( "The size of {0} and its subdirectories is {1} bytes." ,
d, dsize);
}
}
}
|