I'm writing a backup program for our new server. I'm an administrator, and I'm learning a lot. The issue is that I can back up a file on the c:\ drive to the c:\ drive, but not for the drives on the SAN, like when I try to backup a file on the T drive (SAN) to the H drive (server). I tried using SetAttributes like
Why is access to the path denied?
but it basically gives the same error message to try setAttributes as I did when I tried to copy the file. This is a portion of my log:
12/30/2013 2:14:57 PM Successful backup of file C:\test\iceCreamCake_12_30_2013_1414P.docx
12/30/2013 2:14:57 PM exception during backupSystem.UnauthorizedAccessException: Access to the path 'T:\T Drive.vhd' is denied.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.File.SetAttributes(String path, FileAttributes fileAttributes)
at Bak.BackItUp(String fromDrive, String toDrive) in C:\Users\michele\BackupProj\ServerBackup\ServerBackup\Backup.cs:line 36
12/30/2013 2:14:57 PM exception during backupSystem.UnauthorizedAccessException: Access to the path 'S:\SQL Database.vhd' is denied.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.File.SetAttributes(String path, FileAttributes fileAttributes)
at Bak.BackItUp(String fromDrive, String toDrive) in C:\Users\michele\BackupProj\ServerBackup\ServerBackup\Backup.cs:line 36
Shouldn't I be able to run my program to do the backup if I'm logged on as Administrator?
Here's part of the code:
try
{
if (System.IO.File.Exists(fromDrive))
{
result = 4;
if (System.IO.Directory.Exists(toDrive))
{
string oldFileName = Path.GetFileName(fromDrive); //file name only
string sourcePath = Path.GetDirectoryName(fromDrive); //path only
string newFileName = AppendFileNameWithDate(oldFileName); //file name with date added
string destFile = System.IO.Path.Combine(toDrive, newFileName); //full path of final destination with new file name
result = 3;
System.IO.File.SetAttributes(fromDrive, FileAttributes.Normal);
System.IO.File.Copy(fromDrive, destFile, true); //copy backupFileName to toDrive, overwrite destination file if it already exists
if (File.Exists(destFile))
{
Logging.Logging.Instance.Debug("Successful backup of file " + destFile);
result = 2;
}
else
{
result = -2;
Logging.Logging.Instance.Debug("Backup *failure of file " + destFile);
}
}
else
{
Logging.Logging.Instance.Debug("to Drive does not exist: " + toDrive);
result = -1;
}
}
else
{
Logging.Logging.Instance.Debug("from Drive does not exist: " + fromDrive);
result = -1;
}
}
catch (Exception ex)
{
Logging.Logging.Instance.Debug("exception during backup" + ex.ToString());
}
The directory strings are like this:
string cDrive = #"C:\backup\2013\iceCreamCake.docx";
string tDrive = #"T:\T Drive.vhd";
string sDrive = #"S:\SQL Database.vhd";
string cDriveToLocation = #"C:\test";
string tDriveToLocation = #"H:\";
string sDriveToLocation = #"E:\";
string vDriveToLocation = #"G:\";
Thanks,
Michele
Thanks for all your help. I wound up specifically adding (security access to) each of my logins (usxxxxxx and M_CL) to the properties of the files/directories, then editing the privileges to get full control, and also removing all spaces in the file name for the t:\ drive file and the c:\ directories file (it was failing for my M_Cl login but not usxxxx), and it worked for c:\ and t:. We thought the general Users and Administrators file access priviledges would work, but it didn't. The other thing I added was instead of having the complete string for t drive defined with file, I did a path combine like
string sDrive = Path.Combine(#"S:\", #"SQL_Database.vhd");
Related
I am using the following code to save my file into database using entity framework But for some reason it is giving me the error:
'C:/Users/David Buckley/Documents/Visual Studio 2012/Sis/StudentInformationSystem/admin/uploads/' is a physical path, but a virtual path was expected.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Web.HttpException: 'C:/Users/David Buckley/Documents/Visual Studio 2012/Sis/StudentInformationSystem/admin/uploads/' is a physical path, but a virtual path was expected
But it seems to save the file ok in database as the path and filename of C:\Users\David Buckley\Documents\Visual Studio 2012\Sis\StudentInformationSystem\admin\uploads\test.jpg which exsits but i persume I need to save it differently if I want to load it into an image control imageurl field property?.
try
{
int id = Convert.ToInt32(Request.QueryString["id"]);
if (id == -1) // we neeed a new record otherwise get the old one;
{
Student studentRecord = new Student();
_db.AddStudent(studentRecord);
_db.SaveChanges();
newRecordId = studentRecord.Student_ID;
Session["recordid"] = id;
_student = _db.GetStudentById(newRecordId);
}else
_student = _db.GetStudentById(id);
photoUpload.TargetFolder= Server.MapPath("~/admin/uploads/");
string fullPath = Server.MapPath( "~/admin/uploads/");
photoUpload.OverwriteExistingFiles = true;
string newFileName = "";
foreach (UploadedFile file in photoUpload.UploadedFiles)
{
string fileName = "test";
newFileName =fileName + file.GetExtension();
file.SaveAs(Path.Combine(fullPath, newFileName));
// impelement your database insert here...
}
string thumbPath;
thumbPath = ("~/images" + "/" + newFileName);
_student.Image = thumbPath;
_student.Student_Name = txtStudentName.Text;
_student.Student_FatherName = txtFathersName.Text;
_student.Registration_no = txtRegistrationNo.Text;
_student.Address1 = txtAddress1.Text.Trim();
_student.Address2 = txtAddress2.Text.Trim();
_student.Address3 = txtAddress3.Text.Trim();
_student.RelationWithGuadian = txtRelationshipGurdan.Text.Trim();
_student.GurdianName = txtGurdianName.Text.Trim();
_student.LastSchoolAtten = txtLastSchool.Text.Trim();
_student.Contact1 = txtContact1.Text.Trim();
_student.Contact2 = txtContact2.Text.Trim();
_student.DOB = rdDOB.SelectedDate.Value;
_db.SaveChanges();
}
catch (Exception ex)
{
}
To access the file from a web application, you will need to use a virtual path. But you are saving a physical path to the file in the database. Instead of saving the value of Path.Combine(fullPath, newFileName) in the database, you should be saving the value of "~/admin/uploads/" + newFileName.
The above works as long as your uploads/ directory is a descendant of your application directory. Alternatively, you can use a path that points to a directory outside of your application path by explicitly adding a virtual directory.
How to add a virtual directory in IIS express
How to add a virtual directory in IIS
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.
In the constructor of Form1 I did:
contentDirectory = Path.GetDirectoryName(Application.LocalUserAppDataPath) + "\\SF_" + currentDate;
zippedFileDirectory = Path.GetDirectoryName(Application.LocalUserAppDataPath) + "\\Default_ZippedFile_Directory";
if (!Directory.Exists(zippedFileDirectory))
{
Directory.CreateDirectory(zippedFileDirectory);
}
if (!Directory.Exists(contentDirectory))
{
Directory.CreateDirectory(contentDirectory);
}
Checked with breakpoint first time zippedFileDirectory not exist create it and if exist nothing. Same for the contentDirectory.
Now I have the contentDirectory here:
C:\\Users\\bout0_000\\AppData\\Local\\Diagnostic_Tool_Blue_Screen\\Diagnostic Tool Blue Screen\\SF_04-08-13
Inside the contentDirectory I have something like 10 files.
Then zippedFileDirectory is:
C:\\Users\\bout0_000\\AppData\\Local\\Diagnostic_Tool_Blue_Screen\\Diagnostic Tool Blue Screen\\Default_ZippedFile_Directory
This directory is empty.
Then I have this Compress() method:
private void Compress()
{
string source = contentDirectory;
string output = zippedFileDirectory;
string programFilesX86 = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ProgramFilesX86) + "\\Diagnostic Tool\\7z.dll";
if (File.Exists(programFilesX86))
{
SevenZipExtractor.SetLibraryPath(programFilesX86);
}
string programFiles = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ProgramFiles) + "\\Diagnostic Tool\\7z.dll";
if (File.Exists(programFiles))
{
SevenZipExtractor.SetLibraryPath(programFiles);
}
SevenZipCompressor compressor = new SevenZipCompressor();
compressor.ArchiveFormat = OutArchiveFormat.Zip;
compressor.CompressionMode = CompressionMode.Create;
compressor.TempFolderPath = System.IO.Path.GetTempPath();
compressor.CompressDirectory(source, output);
Process.Start(Path.GetFullPath(zippedFileDirectory));
}
For some reason on the line:
compressor.CompressDirectory(source, output);
I'm getting the exception:
Access to the path 'C:\Users\bout0_000\AppData\Local\Diagnostic_Tool_Blue_Screen\Diagnostic Tool Blue Screen\Default_ZippedFile_Directory' is denied.
System.UnauthorizedAccessException was unhandled
HResult=-2147024891
Message=Access to the path 'C:\Users\bout0_000\AppData\Local\Diagnostic_Tool_Blue_Screen\Diagnostic Tool Blue Screen\Default_ZippedFile_Directory' is denied.
I don't get it why this zippedFileDirectory is locked or access denied ?
If I select any other directory as source for example d:\test there is no problem.
It doesn't work because you pass a directory name for the second parameter to CompressDirectory.
You should pass a file name like....
string output = Path.Combine(zippedFileDirectory, "MyZipFile.7z");
.....
compressor.CompressDirectory(source, output);
string sourceDir = #"E:\Images\3\2\1";
string destDir = #"E:\Images\33\22\11";
Directory.Move(sourceDir, destinationDir);
I have to rename directory I use Directory.Move() but gives me error:
Could not find a part of the path.
Folder, to which you are moving, should exist before you move.
Call Directory.Create([path to target folder]) before Directory.Move
It seems that in string destDir = #"E:\Images\33\22\11"; Images\33\22\ does not exist. You cannot create new subdirectories using Directory.Move, so E:\Images\33\22\ must already exist.
See MSDN.
You will need to make sure that the location you are moving the folder to aleady exists. To make it easy you could do something like the following.
Basically you need to make sure that the path where you are moving the file to exists.
string sourceDir = #"E:\Images\3\2\1";
string destName = "1";
string destDir = #"E:\Images\33\22\";
Directory.CreateDirectory(destDir); // Create the location path
Directory.Move(sourceDir, Path.Combine(destDir + destName));
Edit: Added basic error handling.
This is an example with basic error handling to make sure that both the source and destination directory exists.
string sourceDir = #"E:\Images\3\2\1";
string destName = "1";
string destDir = #"E:\Images\33\22\";
if (!Directory.Exists(sourceDir))
{
Console.WriteLine("Source Directory does not exist.");
Console.Read();
//return; // Handle issue where Source Dir does not exist.
}
if (!Directory.Exists(destDir))
{
Console.WriteLine("Destination Directory does exist. Created.");
Directory.CreateDirectory(destDir);
}
if (Directory.Exists(Path.Combine(destDir + destName)))
{
Console.WriteLine("Target Destination already exist.");
Console.Read();
return;
}
Directory.Move(sourceDir, Path.Combine(destDir + destName));
Console.Read();
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.