开发者

creting file/directory in c#

I have some folders/files in several drive like

C:\New Folder
C:\a.txt
D:\New Folder\New Folder
D:\New Folder\a.txt

Now i want to create a directory tree in c drive that will look like

C:\mytempFolder\driveC\New Folder
C:\mytempFold开发者_如何学Pythoner\driveC\a.txt
C:\mytempFolder\driveD\New Folder\New Folder
C:\mytempFolder\driveD\New Folder\a.txt

Is there any shortcut way to implement this in c#?


Use Directory.Create to create the directories:

Directory.Create("c:\mytempFolder\driveC\New Folder");

and to create the files, you'll have to write a text file to that location, like so:

File.Create("D:\New Folder\a.txt").Close;

(It returns a FileSream, so remember to close this afterwards or you will lock the file)

EDIT:

Ok I see what you mean. It that case you need to do something like this:

Loop all files in directory and its sub directories

and when you come across a file or folder, you'll then need to create it in your target folder (i.e. c:\mytempFolder) using the above commands. To get the drive you can simply get the first character in the path string (assuming it will always have a drive letter).

Here's a simple way of doing that but you may need to tweak it to account of filepath inconsistencies:

string targetPath = @"C:\mytempFolder\";
string path = @"D:\New Folder\a.txt";
char driveLetter = path[0];
string filePath = path.SubString(3);
string newFilePath = Path.Combine(targetPath, Path.Combine(String.Format("drive{0}", driveLetter.ToString()), filePath));


   if(System.IO.Directory.Exists("c://gg"))
        {
            System.IO.Directory.CreateDirectory("C:\\gg//");
            System.IO.File.Create("C:\\gg//file.txt");
        }
        else
        {
            Response.Write("ALREADY FOLDER EXIST");
        }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜