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
Related
I'm trying to write exception log messages using StreamWriter in my MVC5 web application.
The main method --
public bool WriteApplicationException(string exp_message)
{
try
{
filename = string.Format("LogMessages\\{0}_{1}.log", "Exception", DateTime.Now.ToShortDateString());
string logFilePath = string.Format(Path.Combine(#"{0}\{1}", AppDomain.CurrentDomain.BaseDirectory, filename));
//logFilePath = logFilePath.Replace(#"\\", #"\");
StringBuilder sb = new StringBuilder();
sb.AppendLine("----------------------------------------------------");
sb.AppendLine(DateTime.Now.ToString());
sb.AppendLine(exp_message);
sb.AppendLine("----------------------------------------------------");
//StreamWriter swr = new StreamWriter(logFilePath, true)
using (StreamWriter swr= File.AppendText(logFilePath))
{
swr.Write(sb.ToString());
swr.Flush();
}
return true;
}
catch (Exception exp)
{
return false;
}
}
I am calling it on the override void OnException in my relevant controller class.
The path that's being generated is as such -
drivelabel:\LogProject.UI\LogProject.UI\LogProject.Web\LogMessages\Exception_3/2/2020.log
But the exception that is being thrown is as such -
{"Could not find a part of the path 'drivelabel:\\LogProject.UI\\LogProject.UI\\LogProject.Web\\LogMessages\\Exception_3\\2\\2020.log'."}
So, could there be any read/write permission issue that is preventing this? Or anything with firewall?
The 2nd one is most unlikely. What could it be? Like I said, the path is very much existent and within the project structure itself. Not outside. What issue here? Any idea?
Thanks.
The message is not telling you that you do not have the right permissions, it is telling you that this path or a part of it does not exist. You need to manually , (or programatically) create that path before you can write to ot.
I know here is some questions about this error in DotNetZip, I've tried all solutions and failed. I'm developing code on my Win8.1 notebook and have no problems, problems begin after deploy to the remote Win2008R2 server...
Here is the problem method:
public bool CreateZIP(string ListStep)
{
Logger logger = LogManager.GetLogger("Task:CreateZIP" + this.TaskGuid);
using (ZipFile zip = new ZipFile())
{
zip.AlternateEncoding = System.Text.Encoding.GetEncoding("cp866");
zip.AlternateEncodingUsage = Ionic.Zip.ZipOption.Always;
...
zip.AddFile(...) loop
...
zip.MaxOutputSegmentSize = Properties.Settings.Default.ZIPSizeLimit * 1024 * 1024;
string zipFolder = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), #"zip-tmp");
string TaskZipFolder = Path.Combine(zipFolder, this.TaskGuid);
try
{
if (!Directory.Exists(zipFolder)) Directory.CreateDirectory(zipFolder);
if (!Directory.Exists(TaskZipFolder)) Directory.CreateDirectory(TaskZipFolder);
zip.TempFileFolder = Path.GetTempPath();
zip.Save(Path.Combine(TaskZipFolder, this.TaskGuid + #".zip"));
}
catch (Exception e)
{
logger.Fatal("Unable to save ZIP into ({0}): {1}", Path.Combine(TaskZipFolder, this.TaskGuid + #".zip"), e.ToString());
throw;
}
}
return true;
}
This code is running on remote server from domain user gfo-svc from C:\Courier\WD directory.
Each object instance has it's GUID, for example e1664582-1bbc-4a9f-a9fe-e7ce4a0a8a55
So the zipFolder variable value is C:\Courier\WD\zip-tmp and TaskZipFolder value is C:\Courier\WD\zip-tmp\e1664582-1bbc-4a9f-a9fe-e7ce4a0a8a55
When this code tries to run it fails with this stack trace:
Unable to save ZIP into (C:\Courier\WD\zip-tmp\e1664582-1bbc-4a9f-a9fe-e7ce4a0a8a55\e1664582-1bbc-4a9f-a9fe-e7ce4a0a8a55.zip): System.UnauthorizedAccessException: Access to the path is denied.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.__Error.WinIOError()
at System.IO.File.InternalMove(String sourceFileName, String destFileName, Boolean checkHost)
at Ionic.Zip.ZipSegmentedStream.TruncateBackward(UInt32 diskNumber, Int64 offset)
at Ionic.Zip.ZipEntry.Write(Stream s)
at Ionic.Zip.ZipFile.Save()
at Ionic.Zip.ZipFile.Save(String fileName)
at Worker.Task.CreateZIP(String ListStep) in Worker.cs:line 844
Line 844 contains this code: zip.Save(Path.Combine(TaskZipFolder, this.TaskGuid + #".zip"));
But in the C:\Courier\WD\zip-tmp\e1664582-1bbc-4a9f-a9fe-e7ce4a0a8a55 folder I can see file e1664582-1bbc-4a9f-a9fe-e7ce4a0a8a55.z01, so the first part of archive was saved before failure.
gfo-svc user has ownership on C:\Courier\WD directory and my code could create zip-tmp directory if it is not exists, and GUID-named directory in it. So the problem is not in Windows Security permissions.
UAC on this remote server is disabled.
What could I do wrong? What might be wrong with my environment? What could I do?
Ok, here is the reason:
This code runs twice on the same host: first time manually from cmd and second time from Windows Task Scheduler.
By default, Task Scheduler starts tasks from C:\windows\system32 and process could not write into it. But my code tried to write into relative to working directory path, so in fact it was trying to write into ...\system32\tmp-dir.
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
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.
We have an ascx custom control (not a web part) hosted in a special Sharepoint page. This page allows users to upload files to our server. Unfortunately permission issues are preventing Sharepoint from saving files to the network location.
The network account attributed to the application pool for the Sharepoint 2007 based site has "modify" and "read" access granted to the location.
We've logged in to a different machine using the credentials used by the application pool account and can create directories and files without any issue at the specified network location.
Is it possible Sharepoint is trying to use some other account to save these files rather than the one set on it's Application Pool in IIS7?
The error we're getting:
Message: Access to the path '\opal\gwl\pictures\L36' is denied.
Stack Trace: at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.Directory.InternalCreateDirectory(String fullPath, String path, DirectorySecurity dirSecurity) at System.IO.Directory.CreateDirectory(String path, DirectorySecurity directorySecurity) at ECan.SharePoint.Web.Applications.MyECan_WaterMeterFormDatalogger.SavePhotos()
Exception Type: System.UnauthorizedAccessException
User: System Account
The code for the SavePhotos function in the ascx code behind file:
protected void SavePhotos()
{
string wellNo = WellNo.Value;
string epoWaterMeterID = EPO_WaterMeterID.Value;
string dirRoot = ConfigurationManager.AppSettings["PhotoDir"];
string map = wellNo.Substring(0, wellNo.IndexOf('/'));
int photoSaveCount = 1;
foreach (string filePath in Request.Files)
{
HttpPostedFile file = (HttpPostedFile)Request.Files[filePath];
if (file.InputStream.Length > 0)
{
try
{
// Create dir if does not exist
string dir = dirRoot + map;
if (!Directory.Exists(dir)) Directory.CreateDirectory(dir);
// Save file
file.SaveAs(dir + #"\" + wellNo.Replace('/', '_') + "-" + epoWaterMeterID.ToString() + "-" + photoSaveCount.ToString() + ".jpg");
photoSaveCount++;
}
catch (Exception ex)
{
Logger.Write(ex);
}
}
}
}
Anyone have any ideas what the issue might be?
I think you have to call the SavePhotos with elevated privildges.
Running the code with elevated priviledges will executes the specified method with Full Control rights even if the user does not otherwise have Full Control.
See link:
http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spsecurity.runwithelevatedprivileges(v=office.12).aspx
Please try the below code:
protected void Button1_Click(object sender, EventArgs e)
{
SPSecurity.CodeToRunElevated elevatedGetSitesAndGroups = new SPSecurity.CodeToRunElevated(SavePhotos);
SPSecurity.RunWithElevatedPrivileges(elevatedGetSitesAndGroups);
}
Have you tried to set the permission of the newly created directory or folder? You can do so by using the DirectorySecurity class within the System.Security.AccessControl Namespace, and specifically the SetAccessControl Method of that class.