2010-10-27 40 views
10

Tôi có một tập hợp các tệp có đường dẫn đầy đủ (root/test/thing1/thing2/file.txt). Tôi muốn foreach trên bộ sưu tập này và thả tệp vào vị trí được xác định trong đường dẫn, tuy nhiên, nếu một số thư mục không tồn tại, tôi muốn chúng được tạo tự động tuyệt vời. Chương trình của tôi có "vị trí thả" mặc định, chẳng hạn như z:/. "Vị trí thả" bắt đầu trống, vì vậy trong ví dụ trên, mục đầu tiên sẽ tự động tạo các thư mục cần thiết để tạo z:/root/test/thing1/thing2/file.txt. Tôi có thể làm cái này như thế nào?Tự động tạo thư mục từ đường dẫn dài

Trả lời

16
foreach (var relativePath in files.Keys) 
{ 
    var fullPath = Path.Combine(defaultLocation, relativePath); 
    var directory = Path.GetDirectoryName(fullPath); 

    Directory.CreateDirectory(directory); 

    saveFile(fullPath, files[relativePath]); 
} 

nơi tệp là IDictionary<string, object>.

10
string somepath = @"z:/root/test/thing1/thing2/file.txt"; 
System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName((somepath)); 
3

Kiểm tra IO namespace (Directory, Path), tôi nghĩ rằng họ sẽ giúp bạn

using System.IO 

Sau đó kiểm tra xem nó ..

string fileName [email protected]"d:/root/test/thing1/thing2/file.txt"; 
string directory = Path.GetDirectoryName(fileName); 
if (!Directory.Exists(directory)) 
    Directory.CreateDirectory(directory); 
7
Directory.CreateDirectory("/root/...") 

Tạo tất cả các thư mục và thư mục con trong đường dẫn được chỉ định

+0

Đồng ý, không cần phải kiểm tra xem thư mục tồn tại như nó thực hiện điều này trong nội bộ. – Squirrel

1
string filename = "c:\\temp\\wibble\\wobble\\file.txt"; 
string dir = Path.GetDirectoryName(filename); 
if (!Directory.Exists(dir)) 
{ 
    Directory.CreateDirectory(dir); 
} 
File.Create(filename); 

với xử lý ngoại lệ phù hợp, tất nhiên.

0

Tôi đã tìm thấy đặt "vị trí mặc định" khi bắt đầu thực hiện để hữu ích và giảm một chút mã dự phòng (ví dụ: Path.Combine(defaultLocation, relativePath)).

Ví dụ:

var defaultLocation = "z:/"; 
Directory.SetCurrentDirectory(defaultLocation); 
Directory.SetCurrentDirectory(AppContext.BaseDirectory); 
Các vấn đề liên quan