来自UWP后台应用程序的文件访问权限 [英] File access permissions from a UWP Background Application

查看:55
本文介绍了来自UWP后台应用程序的文件访问权限的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好


我正在使用Win10 IoT上的Raspberry Pi运行一个小应用程序。


我遇到了一些问题使用NLog进行日志记录工作。我发现问题是我的应用程序不允许删除(或移动)文件,甚至文件本身也已创建。


在我的Pi上我创建了一个日志文件夹。 / p>

c:\ logs


从cmd我运行以下命令:" Folderpermissions c:\logs -e" ;,给APPX读取/写入此文件夹的权限。


我已将程序缩减至:


公共密封类StartupTask:IBackgroundTask

    {

        public void Run(IBackgroundTaskInstance taskInstance)

        {

           试试
            {

                File.AppendAllText(@"c:\\\ logs \ mylog.txt"," Creating file" + Environment.NewLine);

                 File.WriteAllText(@"c:\ logs \test.file","这是一个测试");
$
                 File.Copy(@"c:\ logs \test.file",@" c:\ logs \ test.copy");

      ;            File.Delete(@" c:\ logs \test.file");

                 File.AppendAllText(@" c:\\ mss \ mylog.txt"," File moved" + Environment.NewLine);

             }
            catch(例外e)

            {

                File.AppendAllText(@" c:\ logs \ mylog.txt","移动时例外!" + e.Message + Environment.NewLine);

     ;         }


      }


}



我使用File.Move()等有一些变化on,但这个例子应该足以证明问题。


我创建了一个文件"test.file"里面有一些文字。当我尝试复制它时一切正常,但如果我尝试删除它(或移动它) 我得到一个例外。


例外:System.UnauthorizedAccessException:拒绝访问路径。

  在System.IO.Win32FileSystem.MoveFile(String sourceFullPath,String destFullPath)

  在System.IO.MultiplexingWin32WinRTFileSystem.MoveFile(String sourceFullPath,String destFullPath)

  在System.IO.File.Move(String sourceFileName,String destFileName)



这是预期的行为吗?


我原本以为我可以在我已经授权使用Folderpermissions命令的文件夹中执行我想要的任何文件操作。


Atleast我应该能够删除文件我的应用程序本身已创建。


尝试在应用程序数据文件夹中执行此操作具有相同的行为。


尝试
            {

                File.AppendAllText(@"c:\\\ logs \ mylog.txt"," Creating file" + Environment.NewLine);

                 File.WriteAllText(Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path," test.file"),"This is a test");

     ;             File.Delete(Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path," test.file"));
$
        ;         File.AppendAllText(@" c:\\\ logs \ mylog.txt"," File deleted" + Environment.NewLine);

             }
            catch(例外e)

            {

                File.AppendAllText(@" c:\ logs \mylog.txt"," Exception:" + e.Message + Environment.NewLine);

      ;        }


创建文件

例外:访问路径'C:\ Data\Users\DefaultAccount\AppData\Local \ Packages \\ \\ Application-uwp_9snsj55qnvepy \ Localocal \ test.file'被拒绝。


是否可以启用真正的writeaccess,包括移动和删除文件到UWP后台应用程序的可能性?


当NLog无法归档旧的日志文件(或删除更旧的日志文件)时,我发现了这种行为,所以如果不能对此做任何事情,我基本上无法记录任何内容,因为它会
不可避免地用创建它们的应用程序删除的日志文件填充磁盘。

解决方案

你好LarsQuick,


对于UWP,你可以使用StorageFile和KnownFolders。以下是您可以参考的示例:

 private async void CreateFile()
{
StorageFolder storageFolder = await KnownFolders.GetFolderForUserAsync (null / *当前用户* /,KnownFolderId.PicturesLibrary);
try
{
var sampleFile = await storageFolder.CreateFileAsync(fileName,CreationCollisionOption.ReplaceExisting);
}
catch(exception ex)
{
// I / O错误报告为异常。
System.Diagnostics.Debug.WriteLine(String.Format("创建文件'{0}'时出错:{1}",fileName,ex.Message));
}
}

private async void CopyFile()
{
StorageFile file = await KnownFolders.PicturesLibrary.GetFileAsync(fileName);
if(file!= null)
{
try
{
StorageFolder picturesLibrary = await KnownFolders.GetFolderForUserAsync(null / * current user * /,KnownFolderId.PicturesLibrary) ;
StorageFile fileCopy = await file.CopyAsync(picturesLibrary," sample - Copy.dat",NameCollisionOption.ReplaceExisting);
}
catch(FileNotFoundException)
{
System.Diagnostics.Debug.WriteLine(" FileNotExist");
}
catch(exception ex)
{
// I / O错误报告为异常。
System.Diagnostics.Debug.WriteLine(String.Format(" Error replication file'{0}':{1}",file.Name,ex.Message));
}
}
其他
{
System.Diagnostics.Debug.WriteLine(" FileNotExist");
}
}

private async void DelFile()
{
StorageFile file = await KnownFolders.PicturesLibrary.GetFileAsync(fileName);
if(file!= null)
{
try
{
string filename = file.Name;
await file.DeleteAsync();
}
catch(FileNotFoundException)
{
System.Diagnostics.Debug.WriteLine(" FileNotFoundException");
}
catch(exception ex)
{
// I / O错误报告为异常。
System.Diagnostics.Debug.WriteLine(String.Format(" Error delete file' {0}':{1}",file.Name,ex.Message));
}
}
其他
{
System.Diagnostics.Debug.WriteLine(" FileNotExist");
}
}

注意:确保添加 

<功能> 
< uap:Capability Name =" picturesLibrary" />
< /功能>




或者您可以在
console app



祝你好运,


Rita


Hi

I am making a small application to run on a Raspberry Pi on Win10 IoT.

I had some issues making logging work as I wanted with NLog. I have found out that the problem is that my app is not allowed to delete (or move) files, even files itself has created.

On my Pi I have created a logs folder.

c:\logs

From cmd I have run the following command: "Folderpermissions c:\logs -e", giving APPX read/write rights to this folder.

I have reduced my program to this:

public sealed class StartupTask : IBackgroundTask
    {
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            try
            {
                File.AppendAllText(@"c:\logs\mylog.txt", "Creating file"+Environment.NewLine);
                File.WriteAllText(@"c:\logs\test.file","This is a test");
                File.Copy(@"c:\logs\test.file", @"c:\logs\test.copy");
                File.Delete(@"c:\logs\test.file");
                File.AppendAllText(@"c:\logs\mylog.txt", "File moved"+Environment.NewLine);
            }
            catch (Exception e)
            {
                File.AppendAllText(@"c:\logs\mylog.txt", "Exception when moving! " + e.Message+Environment.NewLine);
            }

      }

}

I have had some variations of this using File.Move() and so on, but this example should be enough to demonstrate the problem.

I create a file "test.file" with some text in it. When I try to copy it everything works fine, but if I try to delete it (or move it)  I get an exception.

Exception: System.UnauthorizedAccessException: Access to the path is denied.
   at System.IO.Win32FileSystem.MoveFile(String sourceFullPath, String destFullPath)
   at System.IO.MultiplexingWin32WinRTFileSystem.MoveFile(String sourceFullPath, String destFullPath)
   at System.IO.File.Move(String sourceFileName, String destFileName)

Is this the intended behaviour?

I was expecting that I could do any file operation I wanted in a folder that I have given permissions to using the Folderpermissions command.

Atleast I should be able to delete the files my app itself has created.

Trying to do this in the applications data folder has the same behaviour.

try
            {
                File.AppendAllText(@"c:\logs\mylog.txt", "Creating file"+Environment.NewLine);
                File.WriteAllText(Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path,"test.file"),"This is a test");
                File.Delete(Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "test.file"));
                File.AppendAllText(@"c:\logs\mylog.txt", "File deleted"+Environment.NewLine);
            }
            catch (Exception e)
            {
                File.AppendAllText(@"c:\logs\mylog.txt", "Exception:" + e.Message+Environment.NewLine);
            }

Creating file
Exception:Access to the path 'C:\Data\Users\DefaultAccount\AppData\Local\Packages\Application-uwp_9snsj55qnvepy\LocalState\test.file' is denied.

Is it possible to enable real writeaccess including the possibility of moving and deleting files to an UWP Background application?

I discovered this behaviour when NLog could not archive old log files (or delete even older logfiles), so if it's impossible to do anything about this I basically can't log anything since it will inevitably fill the disk with logfiles that cant be deleted by the app that created them.

解决方案

Hello LarsQuick,

For UWP, you can use StorageFile and KnownFolders. Here is a sample you can reference:

        private async void CreateFile()
        {
            StorageFolder storageFolder = await KnownFolders.GetFolderForUserAsync(null /* current user */, KnownFolderId.PicturesLibrary);
            try
            {
                var sampleFile = await storageFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
            }
            catch (Exception ex)
            {
                // I/O errors are reported as exceptions.
                System.Diagnostics.Debug.WriteLine(String.Format("Error creating file '{0}': {1}", fileName, ex.Message));
            }
        }

        private async void CopyFile()
        {
            StorageFile file = await KnownFolders.PicturesLibrary.GetFileAsync(fileName);
            if (file != null)
            {
                try
                {
                    StorageFolder picturesLibrary = await KnownFolders.GetFolderForUserAsync(null /* current user */, KnownFolderId.PicturesLibrary);
                    StorageFile fileCopy = await file.CopyAsync(picturesLibrary, "sample - Copy.dat", NameCollisionOption.ReplaceExisting);
                }
                catch (FileNotFoundException)
                {
                    System.Diagnostics.Debug.WriteLine("FileNotExist");
                }
                catch (Exception ex)
                {
                    // I/O errors are reported as exceptions.
                    System.Diagnostics.Debug.WriteLine(String.Format("Error copying file '{0}': {1}", file.Name, ex.Message));
                }
            }
            else
            {
                System.Diagnostics.Debug.WriteLine("FileNotExist");
            }
        }

        private async void DelFile()
        {
            StorageFile file = await KnownFolders.PicturesLibrary.GetFileAsync(fileName);
            if (file != null)
            {
                try
                {
                    string filename = file.Name;
                    await file.DeleteAsync();
                }
                catch (FileNotFoundException)
                {
                    System.Diagnostics.Debug.WriteLine("FileNotFoundException");
                }
                catch (Exception ex)
                {
                    // I/O errors are reported as exceptions.
                    System.Diagnostics.Debug.WriteLine(String.Format("Error deleting file '{0}': {1}", file.Name, ex.Message));
                }
            }
            else
            {
                System.Diagnostics.Debug.WriteLine("FileNotExist");
            }
        }

Note: Make sure add 

  <Capabilities>
    <uap:Capability Name="picturesLibrary" />
  </Capabilities>


Or you can use your code in a console app.

Best regards,

Rita


这篇关于来自UWP后台应用程序的文件访问权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆