简体   繁体   中英

C# System.IO.File.Copy issue

So I needed to make a quick Windows Form app to process a list of files with their directories and copy them to a new dir. Normally I would use a batch file to do this eg

@echo off
mkdir "C:\Users\%username%\Desktop\inst"

:A
ping 127.0.0.1 -n 1 > nul
xcopy "C:\Users\%username%\Desktop\M14.0.1512.400-enu-x64.exe" "C:\Users\%username%\Desktop\inst" /y
xcopy "C:\Users\%username%\AppData\Local\Temp\vcredist.exe" "C:\Users\%username%\Desktop\inst" /y

GOTO A

I know I'm not using the best practices etc. but its a quick script I came up with to help speed up my work. Now doing this for a couple of files is fine but some of the applications I work on havelike 40+ files that I need to copy over and its a bit of a pain having to write a batch file each time.

So I slapped up a simple WF app with a simple input field and a button to start the process.

The user places a list of files (with the path and dir eg C:\\foo\\bar\\hello.txt) into the input field and then the app takes each line from the text box and shoves it into a list after doing some basic filtering eg removing \\n, \\t, \\r and encapsulaing the strings with double quotes if they are not in place already.

new Thread(() =>
{
Thread.CurrentThread.IsBackground = true;

while (run)
{
    foreach (string path in paths)
    {
        Thread.Sleep(100);
        try
        {
            File.Copy(path, dir, true);
        }
        catch (Exception e)
        {
            g.log.WriteToLog("Failed to copy asset: " + e.ToString());

        }
    }
};

}).Start();

When I run that this is what I get in the logs:

//LOGS
21/03/2019 11:25:56  -  Failed to copy asset: System.ArgumentException: Illegal characters in path.   at System.IO.LongPathHelper.Normalize(String path, UInt32 maxPathLength, Boolean checkInvalidCharacters, Boolean expandShortPaths)   at System.IO.Path.NormalizePath(String path, Boolean fullCheck, Int32 maxPathLength, Boolean expandShortPaths)   at System.IO.Path.GetFullPathInternal(String path)   at System.IO.File.InternalCopy(String sourceFileName, String destFileName, Boolean overwrite, Boolean checkHost)   at S2_PackagingTool.Application_Extractor.ExtractAssets() in C:\Users\xxxx\Desktop\GitHub\S2-EnvPrepTool\Application_Extractor.cs:line 98
21/03/2019 11:25:56  -  Path: "C:\Program Files\Freedom Scientific\Runtime JAWS\18.0\jrt.exe" Dir: "C:\Users\xxxx\Desktop\GitHub\S2-EnvPrepTool\bin\Debug\Extracted Assets"

The second line in the logs is a value dump from the path and dir variables.

When I run the code without the while loop and add the path and dir in manually eg

File.Copy(@"C:\foo\bar\hello.txt", @"C:\hello\world", true);

or

File.Copy("C:\\foo\\bar\\hello.txt", "C:\\hello\\world", true);

It works fine.

I will also attatch the filter method incase you guys want to see it. Keep in mind this is quick and dirty so yeah:

public string QuoteEncapsulationFilter(string s)
{
    s = s.Replace("\n", String.Empty);
    s = s.Replace("\r", String.Empty);
    s = s.Replace("\t", String.Empty);
    s = s.Replace("\\", "\\\\");

    if (!s.Contains("\""))
    {
        s = "\"" + s + "\"";
    }

    return s;
}

I have tried looking for an answer everywhere with no luck can someone please shed some light on what I am doing wrong here please. If you need me to provide anymore information please let me know.

Thanks!

You're missing the file name within the File.Copy (string sourceFileName, string destFileName, bool overwrite); function. Your dir path needs the file name.

https://docs.microsoft.com/en-us/dotnet/api/system.io.file.copy?view=netframework-4.7.2

says the following:

destFileName String The name of the destination file. This cannot be a directory.

Edit: To answer your second question in the comments:

new Thread(() =>
{
Thread.CurrentThread.IsBackground = true;

while (run)
{
    foreach (string path in paths)
    {
        Thread.Sleep(100);
        try
        {
            var fileName = Path.GetFileName(path); // Get the file name
            var fullDestination = dir + fileName;  // Complete the uri
            File.Copy(path, fullDestination, true);
        }
        catch (Exception e)
        {
            g.log.WriteToLog("Failed to copy asset: " + e.ToString());

        }
    }
};

}).Start();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM