C# 复制文件代码?

C# 复制文件代码?,c#,C#,我需要一个文件夹上的文件复制到另一个文件夹,我正在使用这个 string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath); foreach (string file in files) { folderBrowserDialog1.ShowDialog(); string xx = folderBrow

我需要一个文件夹上的文件复制到另一个文件夹,我正在使用这个

  string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath);
            foreach (string file in files)
            {
                folderBrowserDialog1.ShowDialog();
                string xx = folderBrowserDialog1.SelectedPath;
                folderBrowserDialog1.ShowDialog();
                string yy = folderBrowserDialog1.SelectedPath;
                File.Copy(xx, yy);
但它不起作用。 为什么?

试试这段代码

我假设您要读取一个文件,然后将其写入新文件

希望能有帮助

string sourceFile;
string newFile = "C:\NewFile\NewFile.txt";
string fileToRead = "C:\ReadFile\ReadFile.txt";
bool overwriteExistingFile = true; //change to false if you want no to overwrite the existing file.

bool isReadSuccess = getDataFromFile(fileToRead, ref sourceFile); 

if (isReadSuccess)
{
    File.Copy(sourceFile, newFile, overwriteExistingFile);
}
else
{
    Console.WriteLine("An error occured :" + sourceFile);
}



//Reader Method you can use this or modify it depending on your needs.
public static bool getDataFromFile(string FileToRead, ref string readMessage)
{
    try
    {
        readMessage = "";
        if (!File.Exists(FileToRead))
        {
            readMessage = "File not found: " + FileToRead;
            return false;
        }
        using (StreamReader r = new StreamReader(FileToRead))
        {
            readMessage = r.ReadToEnd();
        }
        return true;
    }
    catch (Exception ex)
    {
        readMessage = ex.Message;
        return false;
    }
}

似乎在源代码中没有使用文件名。 我举了个例子。文件复制功能


因为您使用的是folderbrowser而不是filebrowser,所以您没有复制文件exaclty不工作意味着什么?请说得更具体一点。我们可以了解一些关于xx和yy的信息吗?因此,File.Copy试图做的事情是显而易见的。它不起作用永远不是一个可接受的问题描述。不在stackoverflow上,不在任何地方。
    public void SaveStockInfoToAnotherFile(string sPath, string dPath, string filename)
    {
        string sourcePath = sPath;
        string destinationPath = dPath;
        string sourceFile = System.IO.Path.Combine(sourcePath, filename);
        string destinationFile = System.IO.Path.Combine(destinationPath, filename);

        if (!System.IO.Directory.Exists(destinationPath))
        {
            System.IO.Directory.CreateDirectory(destinationPath);
        }
        System.IO.File.Copy(sourceFile, destinationFile, true);
    }
    //folderBrowserDialog1.ShowDialog();
    //string xx = folderBrowserDialog1.SelectedPath;
    //string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath);

    //folderBrowserDialog1.ShowDialog();
    //string yy = folderBrowserDialog1.SelectedPath;
    //foreach (string file in files)
    //{
    //    File.Copy(xx + "\\" + Path.GetFileName(file), yy + "\\" + Path.GetFileName(file));