1

ディレクトリを探索し、フォルダを選択して、既存のフォルダの内容をこの新しいディレクトリにコピーしたいと考えています。

このコードを使用していますが、うまくいきません。コピーしたいフォルダは C:\Project です。

            DialogResult result = fd.ShowDialog();
            if (result == System.Windows.Forms.DialogResult.OK)
            {
                MessageBox.Show(fd.SelectedPath.ToString());
            }

            var _SelectedPath = fd.SelectedPath.ToString();
            string sourceFile = @"C:\Project";
            string destinationFile = _SelectedPath;
            string fileName;

            //System.IO.Directory.Move(sourceFile, @"_SelectedPath");

            if (!System.IO.Directory.Exists(@"_SelectedPath"))
            {
                System.IO.Directory.CreateDirectory(@"_SelectedPath");
            }
            if (System.IO.Directory.Exists(sourceFile))
            {
                string[] files = System.IO.Directory.GetFiles(sourceFile);

                // Copy the files and overwrite destination files if they already exist. 
                foreach (string s in files)
                {
                    // Use static Path methods to extract only the file name from the path.
                    fileName = System.IO.Path.GetFileName(s);
                    _SelectedPath = System.IO.Path.Combine(@"_SelectedPath", fileName);
                    System.IO.File.Copy(s, @"_SelectedPath", true);
                }
            }
4

2 に答える 2

2

Microsoft.VisualBasic単一の関数でディレクトリのコピーを処理するため、への参照を追加することで少し簡単にすることができます。必要に応じて、Windows ファイルのコピーの進行状況ダイアログを表示することもできます。

例:

DialogResult result = fd.ShowDialog();
if (result == System.Windows.Forms.DialogResult.OK)
{
    MessageBox.Show(fd.SelectedPath.ToString());
}

string _SelectedPath = fd.SelectedPath.ToString();
string destinationPath = @"C:\Project";

Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory(_SelectedPath, destinationPath);
于 2013-06-15T00:58:52.507 に答える
0

for ループを次のコードに置き換えます

// Copy the files and overwrite destination files if they already exist. 
                foreach (string s in files)
                {
                    // Use static Path methods to extract only the file name from the path.
                    fileName = System.IO.Path.GetFileName(s);
                    string _currFileName = System.IO.Path.Combine(_SelectedPath, fileName);
                    System.IO.File.Copy(s, _currFileName, true);
                }

コードでは、ファイル名を毎回同じ _SelectedPath に追加しています。ソース ディレクトリ (C:\Test) に fileone.txt と filetwo.txt があるかどうかを検討してください。初めてループに入ると、ファイル名はC:\Test\fileone.txtになります。次の反復では、ファイル名はC:\Test\fileone.txt\filetwo.txtになり、エラーが発生します - ファイルが見つかりません。上記のコードは問題を修正します

于 2013-06-15T05:19:45.207 に答える