Click here to Skip to main content
15,885,365 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello, I would like to set my StreamWriter to write my desired value in the line (time in this case) and then sort by value as it is in the leaderboard. I'm trying to create a game in the WPF Application. And my StreamWriter is one of the methods. The problem is that I get an error: System.UnauthorizedAccessException: 'Access to the path 'C:\Ranking.txt' is denied.' So I don't even check if I used my sorting correctly.

What I have tried:

C#
readonly string path = @"C:\Users\info\Desktop\ranking.txt";
private void writeText(string strPath, TimeSpan tsDuration)
        {                   
            StreamWriter str = new StreamWriter(strPath, true);
            string[] line = File.ReadAllLines(strPath);
            Func<string, int> sortBy = line => int.Parse(line.Substring(0, 13));
            var sortedLine = line.Skip(1)
                                  .Take(line.Length - 2)
                                  .OrderBy(sortBy)
                                  .ToArray();
            
            str.WriteLine(tsDuration);
            str.Close();
        }

I know there can be four possibilities why this is so:
1. The caller does not have the required permission.
2. The file is an executable file that is in use.
3. Path is a directory.
4. Path specified a read-only file.
But I don't know how to solve the problem.

Thank you for advice.
Posted
Updated 25-May-21 23:36pm
v2

The system does not allow you to write in the root of the C drive. You should always store user data in one of the locations belonging to the user: Documents, AppData\Local etc.
 
Share this answer
 
v2
I think the exception probably speaks for itself, your application is trying to write to a directory when it doesn't necessarily have the permissions to do so. As a safety precaution the C:\ directory is likely protected by administrator rights. In order to write to that location you would need to run the application as administrator.

If the directory that you're writing your file to is arbitrary then consider using a different one, somewhere which isn't likely to cause security or permission issues. You can use Environment.GetFolderPath()[^] to acquire paths to common directories. A good example might be the desktop, the documents folder, or even having a save file dialog open up so the user can choose the location?
 
Share this answer
 
Comments
Member 15170612 26-May-21 5:29am    
Redoing the path to the desktop did not solve the problem.
To add to what the others have said, have a look here: Where Should I Store My Data?[^] - it suggests some much better places.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900