Permission Issue when persisting custom class by saving to a .txt file

0

I am trying to save my applications viewModel class to a .txt file to allow for persisting it from one session to another.

I am following https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/serialization/walkthrough-persisting-an-object-in-visual-studio as an example.

However, I can't seem to get the permissions correct to allow my code to write to a file.

        private void Save()
        {
            BinaryFormatter bf = new BinaryFormatter();

            // Serialize the Binary Object and save to file
            using (Stream fsout = File.Create("C:\\temp\\viewModel.txt"))
            {
                bf.Serialize(fsout, dataContext);
            }
        }

Error Message:

System.UnauthorizedAccessException
  HResult=0x80070005
  Message=Access to the path 'C:\temp\viewModel.txt' is denied.

Above is how I am trying to create and write to the file. I have tried running Visual Studio 2019 as administrator and that doesn't seem to help. I have tried several other file location to no avail. I checked that the I have permissions to the folder. I am not sure what I am doing wrong.

c#
uwp
asked on Stack Overflow May 26, 2020 by Erik Kinstler • edited May 26, 2020 by Erik Kinstler

3 Answers

1

In UWP, access to files by path is restricted. The recommended practice is to use FileOpenPicker to select files.

But if you just save the data locally, you can use ApplicationData.Current.LocalFolder to access the local application folder.

like this:

private async void Save()
{
    BinaryFormatter bf = new BinaryFormatter();

    var localFolder = ApplicationData.Current.LocalFolder;
    var file = await localFolder.CreateFileAsync("viewModel.txt", CreationCollisionOption.OpenIfExists);

    // Serialize the Binary Object and save to file
    using (Stream fsout = await file.OpenStreamForWriteAsync())
    {
        bf.Serialize(fsout, dataContext);
    }
}

For details about saving data to local files, you can refer to this document:

0

In that case it might be how you're creating/opening the file. Try changing your code to something like this:

using (Stream fsout = File.Open(@"c:\ab\testings.txt", FileMode.Create))
{
    bf.Serialize(fsout, dataContext);
}
answered on Stack Overflow May 26, 2020 by LordPupazz
0

I managed to get the following to work:

    private void Save()
    {
        BinaryFormatter bf = new BinaryFormatter();

        // Serialize the Binary Object and save to file
        using (Stream fsout = new FileStream(System.IO.Path.GetTempPath() + "viewModel.txt", FileMode.Create, FileAccess.ReadWrite, FileShare.None))
        {
            bf.Serialize(fsout, dataContext);
        }
    }

I am however unsure if this is a good place to be storing data for the production application.

answered on Stack Overflow May 26, 2020 by Erik Kinstler

User contributions licensed under CC BY-SA 3.0