Search code examples
angularjswindows-8.1winjs

How can I change file permissions with winjs


I am currently working on a windows 8 winJS/AngularJS application and we want to make some files that are being stored in the LocalState folder to have their permissions changed to be read-only. The files are images taken with the camera and we want to discourage changing the images after saving them.

Any ideas would be great. I am using Windows.Storage.StorageFile.getFileFromPathAsync() to get the file.


Solution

  • You can use the StorageFile.properties.retrievePropertiesAsync and savePropertiesAsync methods to do this. Here's a piece of code that makes a file read-only, where I define the read-only attribute as it's found in the Win32 API:

    var key = "System.FileAttributes";
    var FILE_ATTRIBUTES_READONLY = 1;  //From the Win32 API
    
    var file;  
    
    //Assign some StorageFile to the file variable  
    file.properties.retrievePropertiesAsync([key]).then(function (props) {
         if (props) {
             props[key] |= FILE_ATTRIBUTES_READONLY;
         } else {
             props = new Windows.Foundation.Collections.PropertySet();
             props.insert(key, FILE_ATTRIBUTES_READONLY);
         }  
    
        return file.properties.savePropertiesAsync(props);
    }).done(function () {
        //Any other action
    });
    

    You can use a WinRT component as Rob says, but there's no need.

    I have a full discussion of file properties in my free ebook, Programming Windows Store Apps with HTML, CSS, and JavaScript, Second Edition, Chapter 11, starting on page 592. The code above is directly from page 601.