Reputation: 195
In my application targeting UWP i want to disable a save ("overwrite") button, if the file (modified in my application) has been opened from location where the application cannot write (in this case "Save As" will only be available). The application is allowed however to write to KnownFolders.PicturesLibrary, and I need to determine in code, if given path is located within the PicturesLibrary (or nested subfolder of this location).
I'm able to tell if one path is subfolder of another, but for the StorageFolder
StorageFolder picturesDirectory = KnownFolders.PicturesLibrary;
I get empty Path property value.
So, how can I tell that a given path is or is not located in PicturesLibrary?
Any way to resolve KnownFolders.Pictures library into disk path?
Or should I use something else, other than absolute path, obtained upon file opening to identify later if the file comes from PicturesLibrary?
Upvotes: 1
Views: 384
Reputation: 195
Considering the answer and comments, I've created a simple routine which will tell whether the application will or will not have write access. It is all about creating a small file and testing real ability to save a few bytes. Seems robust, and what is important it verifies effective access, not implied.
The code:
private async Task<bool> CanWriteToSiblingFile(String inputPath)
{
try
{
StorageFile storageFile = await StorageFile.GetFileFromPathAsync(inputPath);
var folder = await storageFile.GetParentAsync();
var newFile = await folder.CreateFileAsync("temp_file.txt", CreationCollisionOption.GenerateUniqueName);
using (Stream stream = await newFile.OpenStreamForWriteAsync())
using (StreamWriter tw = new StreamWriter(stream, Encoding.UTF8))
{
tw.Write("saving ability probe");
tw.Flush();
}
await newFile.DeleteAsync(StorageDeleteOption.PermanentDelete);
return true;
}
catch(Exception ex)
{
return false;
}
}
This answer addresses root business requirement (detecting ability to overwrite), and not the more specific case which I'd wanted to use to implement the business req., - so changing thread title may be suitable…
Best regards, Michael
Upvotes: 0
Reputation: 7737
Here is the way to get the picture library path:
var myPictures = await Windows.Storage.StorageLibrary.GetLibraryAsync(Windows.Storage.KnownLibraryId.Pictures);
string libraryPath = myPictures.SaveFolder.Path;
If you want to determine if an image is located in the picture library, you can do it by comparing the paths.
if(imagePath.StartsWith(libraryPath))
{
// Todo
}
Of course, you need to open access to the image folder.
Best regards.
Upvotes: 1