c#創建文件時怎么創建文件夾


1、通過Path類的Combine方法可以合並路徑。
string activeDir = @"C:\myDir";
string newPath = System.IO.Path.Combine(activeDir, "mySubDirOne");

2、目錄的創建。
創建目錄時如果目錄已存在,則不會重新創建目錄,且不會報錯。創建目錄時會自動創建路徑中各級不存在的目錄。
(1)通過Directory類的CreateDirectory方法創建。
string activeDir = @"C:\myDir";
string newPath = System.IO.Path.Combine(activeDir, "mySubDirOne");
System.IO.Directory.CreateDirectory(newPath);

(1)通過DirectoryInfo的對象創建。
System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(@"C:\myDirTwo\mySubDirThree");
di.Create();

3、文件的創建。
通過Create方法創建文件,會覆蓋同名的現有文件。創建文件時,該文件所在路徑的目錄必須存在,否則報錯。
(1)通過File類的Create方法創建。

string activeDir = @"C:\myDir";
string newPath = System.IO.Path.Combine(activeDir, "mySubDirOne");
System.IO.Directory.CreateDirectory(newPath);

//創建一個空白文件
string fileNameOne = DateTime.Now.ToString("yyyyMMddHHmmssffff")
+ ".txt";
string filePathOne = System.IO.Path.Combine(newPath, fileNameOne);
System.IO.File.Create(filePathOne);

(2)通過FileInfo對象創建。

//通過Combine合並目錄
//然后創建目錄
string activeDir = @"C:\myDir";
string newPath = System.IO.Path.Combine(activeDir, "mySubDirOne");
System.IO.Directory.CreateDirectory(newPath);

//創建一個空白文件
string fileNameOne = DateTime.Now.ToString("yyyyMMddHHmmssffff")
+ ".txt";
string filePathOne = System.IO.Path.Combine(newPath, fileNameOne);
System.IO.FileInfo fi = new System.IO.FileInfo(filePathOne);
fi.Create();

復制目錄文件

//復制單個文件到指定目錄
string fileName = "test.txt";
string sourcePath = @"C:\testDir\subTestDir";
string targetPath = @"C:\testDir\subTestDirTwo";

string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string destFile = System.IO.Path.Combine(targetPath, fileName);

if (!System.IO.Directory.Exists(targetPath))
System.IO.Directory.CreateDirectory(targetPath);

//如果已存在,參數為false時將報錯,參數為true重寫該文件
//當copy方法為兩個參數時,默認重寫為false。
System.IO.File.Copy(sourceFile, destFile, true);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM