1

I create a file that I want to be automatically saved to the Downloads folder of a user. So I used:

StorageFile file = await DownloadsFolder.CreateFileAsync("filename.txt");

But if I create that file again, I get an error stating that file already exists. So I used:

StorageFile file = await DownloadsFolder.CreateFileAsync("filename.txt", CreationCollisionOption.ReplaceExisting);

However that also crashes with the error saying that the parameter does not fall within the expected range. But if I use:

StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync("filename.txt", CreationCollisionOption.ReplaceExisting);

Then it does create the file even if it exists, but I need to create/save the file in the Downloads folder for easier access for the user. I thought of this (attempted) solution because of the issue described here prevented me from adding an attachment to certain e-mail clients.

Community
  • 1
  • 1
Teysz
  • 741
  • 9
  • 33

1 Answers1

0

The method CreateFileAsync (String) uses the FailIfExists option as the default. So when you create that file again, you get an error stating that file already exists.

For more info, see CreationCollisionOption.

The DownloadsFolder.CreateFileAsync("filename.txt", CreationCollisionOption.ReplaceExisting) method crashes with the error saying that the parameter does not fall within the expected range.

Because the app can only access files in the Downloads folder that it created, you can't specify OpenIfExists or ReplaceExisting for this parameter.

Please see DownloadsFolder.CreateFileAsync(String, CreationCollisionOption) document’s Parameters section(the last paragraph).

You can use DownloadsFolder.CreateFileAsync("filename.txt", CreationCollisionOption.GenerateUniqueName) to create the file. It can automatically append a number to the base of the specified name if the file or folder already exists.

If you want to overwrite the exists file in DownloadsFolder. You can use FileSavePicker.PickSaveFileAsync to returns a storageFile object that was created to represent the saved file, and use FileIO.WriteTextAsync(IStorageFile, String) method to write text to the specified file. It can overwrite the old file.

For example:

FileSavePicker savePicker = new FileSavePicker();
savePicker.SuggestedStartLocation = PickerLocationId.Downloads;
savePicker.FileTypeChoices.Add("Simple Line Files", new List<string>() { ".txt" });
savePicker.SuggestedFileName = "filename";
StorageFile file = await savePicker.PickSaveFileAsync();
if (file != null)
{
    await FileIO.WriteTextAsync(file, "hello");
}
Jayden
  • 3,276
  • 1
  • 10
  • 14
  • 1
    It can't have a unique name, because I need to overwrite it, so GenerateUniqueName is not going to work. And I can't use a FileSavePicker because I just want to add the file to an easily accessible location. So instead of the DownloadsFolder, I'm using KnownFolders.ImageLibrary. Which works fine for I'm trying to do. – Teysz Mar 11 '16 at 12:10