Caito103
Caito103

Reputation: 11

Copy a file in a new folder

I have a problem coping a file. I need to copy a .db file and put it in a new folder (called "directory",selected previously with FolderPicker). The code that i have is: (this is for a store app for Windows 8.1)

try{
StorageFile newDB = await StorageFile.GetFileFromPathAsync(directory);
StorageFile originalDB = await StorageFile.GetFileFromPathAsync(Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "AFBIT.db"));
await newDB.CopyAndReplaceAsync(originalDB);
}
catch(Exception ex){
}

I have a exception in neDB, and said "Value does not fall within the expected range." I dont know another way to copy a file in xaml, if u know what is the problem or another way to do this i llbe very grateful.

Upvotes: 1

Views: 441

Answers (2)

Greg
Greg

Reputation: 11480

I'm not sure what your truly inquiring but I believe your attempting is:

public static bool CopyFile(string source, string destination)
{
     if(!File.Exist(source))
          return false;

     if(string.IsNullOrEmpty(destination))
          return false;
     try
     {
          using(var reader = File.Open(source))
               using(var writer = File.Create(destination))
                    reader.CopyTo(writer);

          return true;
     }

     catch(IOException ex) { return false; }
}

Bare in mind this will eat your exception, then return false if it fails at any point for any reason.

That would essentially copy the file, I noticed that your trying to read your local application folder. Be careful, as it often requires Administrator Privileges when it resides in several locations within the Operating System.

Upvotes: 1

MethodMan
MethodMan

Reputation: 18843

I have something similar that I currently use when copying a file CopyFileAsync method I have created see if this can help you in regards to refactoring your code to a working model

public static async Task CopyFileAsync(string sourcePath, string destinationPath)
{
    try
    {
        using (Stream source = File.Open(sourcePath, FileMode.Open))
        {
            using (Stream destination = File.Create(destinationPath))
            {
                await source.CopyToAsync(destination);
            }
        }
    }
    catch (IOException io)
    {
        HttpContext.Current.Response.Write(io.Message); //I use this within a web app change to work for your windows app
    }
}

Upvotes: 2

Related Questions