DirectoryCopy関連
-
22-09-2019 - |
質問
要件:
フォルダー/ディレクトリとその内容をマシンAにマシンBに正常にコピーする必要があります。
コピーを開始する前に、次のポイントを私の要件について考慮する必要があります。
宛先マシンの場合、宛先フォルダーには、ソースフォルダーまたはディレクトリからコピーする必要があるユーザーにアクセス権限があるかどうかがあります。
宛先ディレクトリは非表示または共有されてはならず、既に存在する場合は空にする必要があります。
宛先マシンは、アクセスの資格情報を期待して、それに応じて同じものを処理することを期待しています
これを達成する方法は?
以下のコードでは、痛むことはできません。
using System;
using System.IO;
class DirectoryCopyExample
{
static void Main()
{
DirectoryCopy(".", @".\temp", true);
}
private static void DirectoryCopy(
string sourceDirName, string destDirName, bool copySubDirs)
{
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
DirectoryInfo[] dirs = dir.GetDirectories();
// If the source directory does not exist, throw an exception.
if (!dir.Exists)
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourceDirName);
}
// If the destination directory does not exist, create it.
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
// Get the file contents of the directory to copy.
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
// Create the path to the new copy of the file.
string temppath = Path.Combine(destDirName, file.Name);
// Copy the file.
file.CopyTo(temppath, false);
}
// If copySubDirs is true, copy the subdirectories.
if (copySubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
// Create the subdirectory.
string temppath = Path.Combine(destDirName, subdir.Name);
// Copy the subdirectories.
DirectoryCopy(subdir.FullName, temppath, copySubDirs);
}
}
}
}
解決
ファイルの送信については、ここであなた自身の質問を見ることができます:機械から機械ファイルの転送 そしてここでいくつかの短いスクリプト:http://www.eggheadcafe.com/community/aspnet/2/10076226/file-transfer-from-one-ma.aspx
よりも、fileInfoとdirectoryInfoを使用します - 属性を取得します。http://msdn.microsoft.com/en-us/library/system.io.directoryinfo%28vs.71%29.aspx
リモートフォルダーへの接続は、DirectorySecurityを使用して実行できます。http://msdn.microsoft.com/en-us/library/system.security.accesscontrol.directorysecurity.aspx
楽しみ!
他のヒント
これらすべての情報があります DirectoryInfo
あなたの DirectoryInfo dirInfo = new DirectoryInfo(path)
;
コードスニペットは、同じマシン内ではなく、2つのマシン間でファイルを実際にコピーしません。これはあなたの主な方法から明らかです。
マシン間とそれも非共有の場所に転送したい場合は、おそらくソケットをチェックする必要があります。
適切なアクセス許可セットを備えた共有場所の場合、file.copyはあなたのために助けを与えます。
をチェックしてください System.Security.AccessControl.DirectorySecurity class:system.io.directory.getacescontrol( "dir_name")を呼び出すと、directorysecurityオブジェクトを取得できます。これがリモートマシンのディレクトリに関する情報を取得できるかどうかはわかりません。