Skip to content

Commit

Permalink
Fixed an issue where files dragged in from Files were read only
Browse files Browse the repository at this point in the history
  • Loading branch information
yaira2 committed May 11, 2021
1 parent 9403990 commit 8d0b1b1
Showing 1 changed file with 32 additions and 2 deletions.
34 changes: 32 additions & 2 deletions src/QuickPad.Data/QuickPad.Data/StorageFileDataProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using QuickPad.Standard.Data;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Windows.Storage;
Expand All @@ -22,6 +23,24 @@ public async Task<byte[]> LoadDataAsync(StorageFile file)
return bytes;
}

public static bool IsFileReadOnly(StorageFile file)
{
return (file.Attributes & Windows.Storage.FileAttributes.ReadOnly) != 0;
}

public static async Task<bool> IsFileWritable(StorageFile file)
{
try
{
using (var stream = await file.OpenStreamForWriteAsync()) { }
return true;
}
catch (Exception)
{
return false;
}
}

public async Task<string> SaveDataAsync(StorageFileWrapper<StorageFile> file, IWriter writer, Encoding encoding)
{
List<byte> allBytes = new List<byte>();
Expand All @@ -38,8 +57,19 @@ public async Task<string> SaveDataAsync(StorageFileWrapper<StorageFile> file, IW

var bytes = allBytes.ToArray();

// Create sample file; replace if exists.
await PathIO.WriteBytesAsync(file.Path, bytes);

if (IsFileReadOnly(file.File) || !await IsFileWritable(file.File))
{
// For file(s) dragged into Quick Pad, they are read-only
// StorageFile API won't work but can be overwritten by Win32 PathIO API
// In case the file is actually read-only, WriteBytesAsync will throw UnauthorizedAccessException exception
await PathIO.WriteBytesAsync(file.Path, bytes);
}
else // Use FileIO API to save
{
// Create file; replace if exists.
await FileIO.WriteBytesAsync(file.File, bytes);
}

return $"{file.Name} was saved.";
}
Expand Down

0 comments on commit 8d0b1b1

Please sign in to comment.