0

I am creating a windows form application. for security reason i want to store licence information into a text file and want to encrypt it.

var serializer = new XmlSerializer(typeof(Licence));

var saveData = new Licence
{
    ProductId = txtProductID.Text,

    ProductKey = txtProductKey.Text,

    CreatedDate = validate.CreationDate,

    ExpireDate = validate.ExpireDate,

    DaysLeft = validate.DaysLeft
};

using (var writeFile = File.OpenWrite("data.txt"))
{
    serializer.Serialize(writeFile, saveData);
}

using this code i can able to create text file successfully. but when i publish this project and install it it gives me error. error message is...

Access to the path "C:\Program Files (x86)\WebenixSystem\Metro Whole Sale\data.txt" is denied.

************** Exception Text ************** System.UnauthorizedAccessException: Access to the path 'C:\Program Files (x86)\WebenixSystem\Metro Whole Sale\data.txt' is denied.

How can i resolve this issue, and how can i encrypt this txt file? please help...

Community
  • 1
  • 1
MD MASUM
  • 49
  • 11
  • save it in the users directory, or require your app to run with admin rights – BugFinder Sep 10 '18 at 11:16
  • 1
    Take a look at [Where is the correct place to store my application specific data?](https://stackoverflow.com/questions/10563148/where-is-the-correct-place-to-store-my-application-specific-data) – Alex K. Sep 10 '18 at 11:18
  • Take a look at https://stackoverflow.com/questions/7590446/set-file-permissions-in-c-sharp – Ncs Sep 10 '18 at 11:26
  • 3
    @RBK making the app run with admin rights is rarely, if ever, the correct solution. For something as simple as saving a file, it's complete overkill and opens up security issues. This suggestion is like hearing echoes from the early 2000s and all the Windows xp security hell. – ADyson Sep 10 '18 at 11:27

2 Answers2

1

As the error suggests - you do not have permission to access the path you are trying to save the file to.
As the file will be encrypted, you do not have to hide it. Therefore, you could save it in the documents folder of the users account.

Using this line of code will return the path to the 'My Documents' folder. You can create a new folder within there or save the file directly to this path.

Note this is a relative path so it will work for all users.

String pathToDocuments = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
Aleksandar Zoric
  • 1,343
  • 3
  • 18
  • 45
0

Also to note: The license information won't be shared between different users. If user will logon with different account, the license data won't be found, because each user has its own "MyDocuments", "AppData" etc...

Tiber Septim
  • 315
  • 3
  • 11