簡體   English   中英

在.net中,有一種簡單的方法可以復制文件,其中源和目標可以是文件名或目錄名?

[英]In .net is there an easy way to copy files where the source and target could be either file or directory names?

基本上,我想要一個函數,該函數可以為源提供字符串,該字符串可以是目錄名或文件名,然后可以是目標,也可以是目錄名或文件名。 如果您嘗試將目錄復制到特定文件名,則失敗,但是在所有其他情況下都可以使用。 我還希望能夠傳遞其他參數,以告訴它在復制之前覆蓋文件和/或刪除目標目錄,以及在目錄不存在時創建該目錄。 那里已經有類似的東西了嗎?

這是我從谷歌搜索中獲得的基本測試...(加上一些修改)

// get the file attributes for file or directory
string someStringFromUserInput = Console.ReadLine();
FileAttributes attr = File.GetAttributes(someStringFromUserInput);

//detect whether its a directory or file
if((attr & FileAttributes.Directory) == FileAttributes.Directory)
{
    Console.WriteLine("It's a directory");
    //Do some transfer method
}
else
{
    Console.WriteLine("It's a file");
    //Do some transfer method
}

編輯:這是一個非常基本的示例,當它們嘗試命中不存在的文件夾時,您還希望處理FileNotFoundExceptions。 但是顯然,您仍然需要添加邏輯來進行復制。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM