I'm currently trying to delete all files in a folder (Recently opened files), but without any luck, I get the message: "Access to the path 'C:\Users\User\Recent' is denied." . I've been looking around to see if there were any solutions, but unfortunately I can't find anything.
String recent = Environment.ExpandEnvironmentVariables("%USERPROFILE%") + "\\Recent";
EmptyFolderContents(recent);
private void EmptyFolderContents(string folderName)
{
foreach (var Folder in Directory.GetDirectories(folderName))
{
try
{
Directory.Delete(Folder, true);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
foreach (var Files in Directory.GetFiles(folderName))
{
try
{
File.Delete(Files);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex);
}
}
}
The reason you are getting the Access Denied error is because you can't just delete files from that folder. They are virtual paths to real files. There is probably a better way to do what you are doing.
Here is an alternative that I found here. It uses WinAPI, which is never fun, but it works.
//you'll need to add this.
using System.Runtime.InteropServices;
[DllImport("shell32.dll")]
public static extern void SHAddToRecentDocs(ShellAddToRecentDocsFlags flag, IntPtr pidl);
public enum ShellAddToRecentDocsFlags
{
Pidl = 0x001,
Path = 0x002,
}
//then call this from your method
SHAddToRecentDocs(ShellAddToRecentDocsFlags.Pidl, IntPtr.Zero);
Your error message seems to show that you're missing a backslash:
Access to the path 'C:Users\User\Recent' is denied.
(after the C:)
I Use Permissions Time Machine v1.1 to restore default permissions and remove "Access is denied" message for folder or files or registry keys or windows services or wmi objects it's free and fast and easy
download it from amyd projects blog
Related
I know this is a common problem with a lot of related topics on here. But none of them seem to work for me.
I have code that works on a production system that I've copied across to my local home computer:
private static void WriteToLog(string logText, string logPath)
{
try
{
using (StreamWriter outputFile = File.AppendText(logPath))
{
outputFile.WriteLine(DateTime.Now.ToString() + "|| " + Regex.Replace(logText, #"\t|\n|\r", ""));
}
}
catch (IOException ex)
{
//what do?
throw ex;
}
}
The line using (StreamWriter outputFile = File.AppendText(logPath)) throws the classic exception:
System.UnauthorizedAccessException: 'Access to the path
'C:\Users\Jaso\Documents\DataChecker_Logs\schema_a-academic_attainment.txt'
is denied.'
At runtime the path variable contains "C:\\Users\\Jaso\\Documents\\DataChecker_Logs\\schema_a-academic_attainment.txt"
The Security of the folder in question looks like this:
When I find the user the process is run under using WindowsIdentity.GetCurrent().Name;, the value returned is "DESKTOP-LMMBET3\\Jaso" which according to the folder's settings (above screenshot) is a principal with full control!!
Windows 10 machine.
GRRR!!!
Check the permission of the file itself not the folder
if you don't have the permission to access the file this error will be thrown
System.UnauthorizedAccessException
In my network, there are some files whose access is simply blocked.
A user cannot open nor read the file.
When I try to open the file, the only message that I get is "Access Denied".
bool isReadOnly = ((File.GetAttributes(Path) & FileAttributes.ReadOnly) == FileAttributes.ReadOnly);
I tried other options available under FileAttributes class. Nothing is matched for "Access Denied".
In short, how do I know whether a file is access-denied to me or not in c#. I am using WPF and visual studio .net 2010
Whenever I try to access it through code, I simply get an exception. When I try to open it manually I get something like "Access Denied."
try
{
IEs = from file in Directory.EnumerateFiles(sDirectoryToBeSearched, sValidExtensions, SearchOption.AllDirectories)
from str in File.ReadLines(file)
where (str.IndexOf(sSearchItem, StringComparison.OrdinalIgnoreCase) >= 0)
select file;
}
catch
{
MessageBox ("Exception arised");
}
Even If used try catch, exception is not handled because of LINQ query. Any solutions ?>
Instead of using LINQ try using recursion, that way if a file or folder access is denied the rest of procedure will continue. Example bellow.
private void SearchDirectory(string folder)
{
foreach (string file in Directory.GetFiles(folder))
{
try
{
// do work;
}
catch
{
// access to the file has been denied
}
}
foreach (string subDir in Directory.GetDirectories(folder))
{
try
{
SearchDirectory(subDir);
}
catch
{
// access to the folder has been denied
}
}
}
You don't have to check the FileAttributes, you need to check the security lists.
You can look at the example here to see how to work with the FileSecurity class.
I have a small deploy tool that I'm upgrading. The tool takes a version of code from the build box, updates SVN, and then plops it on X servers (A deploy moves specific parts of the deploy installs to different servers within the stack).
What is happening now is when it's ran on anything other than our build box, it will not work due to securities.
Our build box is internal and on our own domain. The servers we're copying to are on a high security domain. I have used the techniques explained here: Accessing Password Protected Network Drives in Windows in C#? for accessing files / data on those domain drives so i don't need to map it.
But here's the catch.
Build box - Domain A
Deploy Server - Domain B
Deploy Server 2 - Domain B
My box has complete control over our Build Box because the dev's run as administrators, and it is on our domain. However, once I impersonate my login so I'm on Domain B, I can't access my Domain A build box.
This is an internal utility, and any help would be appreciated.
*If there's extensive work on this instead of copying I can open new threads and run a command line to get these files from SVN on each server as that is a possibility instead of copying. We keep all deploy install files in SVN.
IntPtr token;
if (!Security.Access.LogonUser("ChuckNorris", "a_small_bunny[0]", "OfficeSpace", Security.Enums.LogonType.NewCredentials, Security.Enums.LogonProvider.Default, out token))
{
throw new Win32Exception();
}
try
{
IntPtr dToken;
if (!Security.Access.DuplicateToken(token, Security.Enums.SecurityImpersonationLevel.Impersonation, out dToken))
throw new Win32Exception();
try
{
using (WindowsImpersonationContext iContext = new WindowsIdentity(dToken).Impersonate())
{
Directory.CreateDirectory(destDir); //Works Here as I have impersonation
// copy each file to destination
//This will bomb as my user is now linked to the prod domain.
foreach (string file in Directory.GetFiles(srcDir))
{
// update property bag
UpdatePropertyBag(
propertyBag,
PropertyBag.Step,
"Copying [" + file + "] to [" + destDir + "]");
// copy each file
File.Copy(file, CombinePath(destDir, Path.GetFileName(file)));
}
// deal with each file/folder
foreach (string dir in Directory.GetDirectories(srcDir))
{
// copy each subdirectory
CopyDirectory(propertyBag, srcDir, destDir, Path.GetFileName(dir));
}
iContext.Undo();
}
}
catch (Exception ex)
{
}
finally
{
if (dToken != IntPtr.Zero)
{
if (!Security.Access.CloseHandle(dToken))
{
// Uncomment if you need to know this case.
////throw new Win32Exception();
}
}
}
}
catch (Exception ex)
{
}
finally
{
if (token != IntPtr.Zero)
{
if (!Security.Access.CloseHandle(token))
{
// Uncomment if you need to know this case.
////throw new Win32Exception();
}
}
}
I may have missed something in the flow above but can you:
Impersonate domain A
Copy to a shared location with permissions for both domains.
Impersonate domain b, move to final location.
Other options are to read the file details, load into memory, and write to the destination and preserve timestamp if necessary.
I have this simple code:
System.Drawing.Bitmap bm = bitmapSourceToBitmap(source);
try
{
bm.Save(#"C:\Seva\testeImagem.jpg");
}
catch (Exception ex)
{
}
This throws: Generic Error GDI+.
Anyway, I seached and people say that the problem is with permissions. How can I give permissions to it? Thanks
First find out under what credentials the code is running.
Then check (and, when needed, fix) the security/NTFS settings of the Seva folder.
Especially when this code is running from within a website or service the account will not have permissions to write to the folder.
instead of saving to C:\Seva\testeImagem.jpg why not try saving to
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
"testeImagem.jpg");
You must ensure that the Seva folder exists under C:\ and ensure that the current user has permissions to write to\create this folder. Also, its considered bad practice to write to folders that the user doesn't own. If the user is Running As A Normal User (not an admin) failure to do so results in permission exceptions.
Could you test if the folder exists?
void BitmapCopy(System.Drawing.Bitmap source, string filename) {
if (!String.IsNullOrEmpty(filename) && (source != null)) {
string dirName = #"C:\Seva";
if (!System.IO.Directory.Exists(dirName)) {
dirName = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
}
string bmpFile = System.IO.Path.Combine(dirName, filename);
System.Drawing.Bitmap bm = bitmapSourceToBitmap(source);
try {
bm.Save(bmpFile);
} catch (ArgumentNullException ex) {
Console.WriteLine(ex.Message);
} catch (System.Runtime.InteropServices.ExternalException ex) {
Console.WriteLine(ex.Message);
}
}
}
I have some C# code that tries to get the Favorites for the currently logged in user. The code is part of a Taskbar Toolbar that gets loaded into the Windows Explorer process. I have a user who is using Windows Vista with UAC enabled on a domain that either has Roaming Profiles or Folder Redirection setup and enabled. When calling Directory.GetDirectories on the Favorites path, it throws "System.IO.DirectoryNotFoundException: Could not find a part of the path 'C:\Users\\Favorites\". Other users on other domains that do not have Roaming Profiles or Folder Redirection setup do not have this issue.
The user also reported that copying the path from the failed logs into the run prompt fails to load the path, but if they navigate to the path directly using explorer and then copy and paste that path into the run prompt, it works. He sent me both paths and they are exactly identical which doesn't make any sense at all.
My theory is that this is caused by the Folder Redirection where that path is actually pointing to a share on the server but the redirection is failing when trying to access the subdirectories (of the directoryInfo returned from Directory.GetDirectories). The initial directory works but all subdirectories of the initial directory fail to redirect correctly.
Has anyone come across a situation like this and/or know a workaround to gain proper access to redirected folders?
private void GetFavorites()
{
try
{
System.IO.DirectoryInfo dirInfo = new System.IO.DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.Favorites));
AddFavorites(dirInfo);
}
catch
{
}
}
private void AddFavorites(DirectoryInfo dirInfo)
{
foreach (System.IO.FileInfo fileInfo in dirInfo.GetFiles("*.url"))
{
//string alias = fileInfo.Name.Replace(".url", "");
if (!ItemsBookmarks.ContainsKey(fileInfo.Name))
ItemsBookmarks.Add(fileInfo.Name, fileInfo.Name);
}
foreach (System.IO.FileInfo fileInfo in dirInfo.GetFiles("*.lnk"))
{
if (!ItemsBookmarks.ContainsKey(fileInfo.Name))
ItemsBookmarks.Add(fileInfo.Name, fileInfo.Name);
}
foreach (System.IO.DirectoryInfo objDir in dirInfo.GetDirectories())
{
AddFavorites(objDir);
}
}
Thanks,
John
I believe the problem you are experiencing is related to Reparse Points.
See: http://msdn.microsoft.com/en-us/library/bb513869.aspx
See: What is the best way to check for reparse point in .net (c#)?
The problem can be avoided by using the following syntax:
private void AddFavorites(string dirPath)
{
try
{
foreach (string fileName in Directory.GetFiles(dirPath, "*.*", SearchOption.TopDirectoryOnly))
{
//string alias = fileInfo.Name.Replace(".url", "");
if (!ItemsBookmarks.ContainsKey(fileInfo.Name))
{
ItemsBookmarks.Add(fileName);
}
}
foreach (string subDirName in Directory.GetDirectories(dirPath, "*.*", SearchOption.TopDirectoryOnly))
{
AddFavorites(objDir);
}
}
catch
{
//error getting files or subdirs... permissions issue?
//throw
}
}