简体   繁体   中英

Access to this directory is denied

I have discovered a problem with using a StreamReader to read a text file. If you use it, it somehow renders the directory the file itself is located unmovable. For example-

cuLocation = "C:\\Users\\WoopyCat\\AppData\\Roaming\\.minecraft\\currentUser.txt";
System.IO.StreamReader objReader = new System.IO.StreamReader(cuLocation);
currentUser = objReader.ReadLine();
TBcurrentUser.Text = "The current user is " + currentUser + ".";

All this happens upon form load. Then I have a button click event set up where this happens-

System.IO.Directory.Move("C:\\Users\\WoopyCat\\AppData\\Roaming\\.minecraft", "C:\\Users\\WoopyCat\\AppData\\Roaming\\.MCSwitcher\\" + currentUser);

However, the IDE says access to .minecraft is denied. But if I remove this code-

cuLocation = "C:\\Users\\WoopyCat\\AppData\\Roaming\\.minecraft\\currentUser.txt";
System.IO.StreamReader objReader = new System.IO.StreamReader(cuLocation);
currentUser = objReader.ReadLine();

And replace it with this code-

currentUser = "Paul";

It works perfectly. It can access .minecraft. But I need to read the currentUser.txt file in order for my program to work. Any help?

Again, to reiterate- this code-

cuLocation = "C:\\Users\\WoopyCat\\AppData\\Roaming\\.minecraft\\currentUser.txt";
System.IO.StreamReader objReader = new System.IO.StreamReader(cuLocation);
currentUser = objReader.ReadLine();

Prevents this code from working-

 System.IO.Directory.Move("C:\\Users\\WoopyCat\\AppData\\Roaming\\.minecraft", "C:\\Users\\WoopyCat\\AppData\\Roaming\\.MCSwitcher\\" + currentUser);

You do close obj.Reader before the move using objReader.Close() , right? Having a stream opened to the file will prevent it being moved. If that isnt the case, theres an application (handle I think it's called) that will let you see what has access to a file, so you can see whats preventing you from moving the dir.

The only possible reason I can think of is you are not really the WoopyCat user, here is the correct way to get the path based of the currently running user.

var roamingFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); //This equals the \AppData\Roaming\ folder for the current user
Directory.Move(Path.Combine(roamingFolder, ".minecraft"), Path.Combine(roamingFolder,currentUser));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM