Access to the path is denied from get assembly version of file - c#

I create web form application to upload file (.exe) and i get assembly version of file but i have a problem is 'access to the path is denied' when i am deleting file after get version.
Code :
protected void uploadBT_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
try
{
/** Save file to tmp **/
string filename = FileUpload1.PostedFile.FileName;
FileUpload1.PostedFile.SaveAs(Server.MapPath("~/FilesUploaded/tmp/" + filename));
/** get assembly version **/
Assembly asb = Assembly.LoadFile(Server.MapPath("~/FilesUploaded/tmp/" + filename));
string version = asb.GetName().Version.ToString();
Directory.Delete(Server.MapPath("~/FilesUploaded/tmp"), true);
Thread.Sleep(5);
Directory.CreateDirectory(Server.MapPath("~/FilesUploaded/tmp"));
/** Save each versions **/
Directory.CreateDirectory(Server.MapPath("~/FilesUploaded/" + version));
FileUpload1.PostedFile.SaveAs(Server.MapPath("~/FilesUploaded/" + version + "/" + filename));
}
catch (Exception ex)
{
errTxt.Text = ex.Message.ToString();
}
}
}

IIS most likely blocking .exe, you'd need to allow it through the MIME types.

The hosting company should be able to grant the permissions to that folder to aspnet user since it appears that is your hosted directory but I could be wrong. Have you asked their support about this error?

Related

Access files from Network shared folder

I am accessing one folder with csv file under it by c# code. I have network path like "\NL0000NAS0007.dir.xyz.com\webtest\SERVERS\NLWSL086\personnel\people\PROD". While calling with below code it is appending "c:" earlier to this url so I am not able to get the files.
Below is my code snippet.
{
try
{
WriteLogFile.WriteLog(this.Configuration.GetValue<string>("logFile"), "Copy CSV File to Server", MessageType.Info);
//string projectPath = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;
string projectPath = #"D:\Paracomcsv\";
string folderName = Path.Combine(projectPath, "CsvFiles_" + DateTime.Now.ToString("MM_dd_yyyy"));
string[] files = Directory.GetFiles(sourcePath);
if (!Directory.Exists(folderName))
{
Directory.CreateDirectory(folderName);
}
if (files.Length > 0)
{
// Copy the files and overwrite destination files if they already exist.
foreach (string s in files)
{
// Use static Path methods to extract only the file name from the path.
var fileName = Path.GetFileName(s);
var destFile = Path.Combine(folderName, fileName);
System.IO.File.Copy(s, destFile, true);
}
}
else
{
WriteLogFile.WriteLog(this.Configuration.GetValue<string>("logFile"), "File Doesn't Exist", MessageType.Error);
}
}
catch (Exception ex)
{
WriteLogFile.WriteLog(this.Configuration.GetValue<string>("logFile"), ex.Message, MessageType.Error);
throw ex;
}
}
I am getting the error while calling Directory.GetFiles. Anyone had the same issue, if yes please let me know how to call remote network shared file.
Thanks
The code snippet cant be the full source code. It is unclear how the variables are initialised. But given your network path of "\NL0000NAS0007.dir.xyz.com\webtest\SERVERS\NLWSL086\personnel\people\PROD" it is very clear, that it doesnt function. The path starts with a single \ character, so the System.IO API assumes you mean a relative path to whatever is the current directory or drive . And this could be "C:"...

Folder Rename using Directory.Move(): Access to Path is Denied

I have Common Network Shared Folder When Folder Rename using Directory. Move(): Access to Path is Denied, Actual Problem is When Folder is open by another System or another process, If Any possible to rename the folder or Close the Folder Open by another system or another process
My Code
static void moveToShare()
{
if (!Directory.Exists("\\Share")) Directory.CreateDirectory("\\Share");
string timestamp = DateTime.Now.ToString("yyyyMMddHHmms");
try
{
Directory.Move("\\Output", "\\Share\\" + timestamp);
}
catch(Exception e)
{
Console.WriteLine("Cant Move Folder: " + e.Message);
}
}
You must gain access.
AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
WindowsIdentity idnt = new WindowsIdentity(username, password);
WindowsImpersonationContext context = idnt.Impersonate();
if (!Directory.Exists("\\Share"))
Directory.CreateDirectory("\\Share");
string timestamp = DateTime.Now.ToString("yyyyMMddHHmms");
try
{
Directory.Move("\\Output", "\\Share\\" + timestamp);
}
catch(Exception e)
{
Console.WriteLine("Cant Move Folder: " + e.Message);
}
context.Undo();

C# Windows Service Not Compressing Folder Correctly

Im currently building a Windows service that will be used to create backups of logs. Currently, the logs are stored at the path E:\Logs and intent is to copy the contents, timestamp their new folder and compress it. After this, you should have E:\Logs and E:\Logs_[Timestamp].zip. The zip will be moved to C:\Backups\ for later processing. Currently, I am using the following to try and zip the log folder:
var logDirectory = "E://Logs";
var timeStamp = DateTime.Now.ToString("yyyyMMddHHmm");
var zippedFolder = logDirectory + "_" + timeStamp + ".zip";
System.IO.Compression.ZipFile.CreateFromDirectory(logDirectory, zippedFolder);
While this appears to create a zip folder, I get the error Windows cannot open the folder. The Compressed (zipped) Folder E:\Logs_201805161035.zip is invalid.
To address any troubleshooting issues, the service is running with an AD account that has a sufficient permission level to perform administrative tasks. Another thing to consider is that the service kicks off when its FileSystemWatcher detects a new zip folder in the path C:\Aggregate. Since there are many zip folders that are added to C:\Aggregate at once, the FileSystemWatcher creates a new Task for each zip found. You can see how this works in the following:
private void FileFoundInDrops(object sender, FileSystemEventArgs e)
{
var aggregatePath = new DirectoryInfo("C://Aggregate");
if (e.FullPath.Contains(".zip"))
{
Task task = Task.Factory.StartNew(() =>
{
try
{
var logDirectory = "E://Logs";
var timeStamp = DateTime.Now.ToString("yyyyMMddHHmm");
var zippedFolder = logDirectory + "_" + timeStamp + ".zip";
ZipFile.CreateFromDirectory(logDirectory, zippedFolder);
}
catch (Exception ex)
{
Log.WriteLine(System.DateTime.Now.ToString() + " - ERROR: " + ex);
}
});
task.Dispose();
}
}
How can I get around the error I am receiving? Any help would be appreciated!

The remote server returned an error: (405) Method Allowed

I know that this is a common problem facing over, but am getting this this problem with a different scenario.
am going to explain scenario here
I created a two different projects in a solution. The image containing folder that i want to use for save, i-e upload is outside of these above projects but under same solution.
Actually i created virtual directly (My File Server) on IIS server of this folder
here is my code.
private void SaveData()
{
string filename = Path.GetFileName(ImageUpload.PostedFile.FileName);
string servpath = Server.MapPath(ConfigurationManager.AppSettings["TempFolder"]);
ImageUpload.SaveAs(servpath + filename);
string remoteServerPath = ConfigurationManager.AppSettings["ProductImagesPath"] + filename;
try
{
WebClient client = new WebClient();
client.UploadFile(remoteServerPath, servpath + filename);
}
catch (Exception ex)
{
throw ex;
}
objProductsCustom.ProductName = txtProductName.Text;
objProductsCustom.ProductDiscription = txtAddDiscription.Text;
objProductsCustom.ProductPrice = txtPrice.Text;
objProductsCustom.Quantity = txtQuantity.Text;
objProductsCustom.ImagePath = "servpath" + filename;
int productID = objProductsManager.CreatProduct(objProductsCustom);
}
Where on try-catch, I found "The remote server returned an error: (405) Method Allowed." error. I am stuck.
EDIT
This is the remoteserverpath :
http://localhost/ProductImages/untitled.bmp
And this is the file which i am uploading to remoteserverpath:
C:\Documents and Settings\saltaf\My Documents\Visual Studio 2010\Projects \OnlineShoppingSystem\OnlineShoppingSiteAdminPanel\Temp\Images\untitled.bmp
And this is my call:
webclient.UploadFile(http://localhost/ProductImages/untitled.bmp,C:\Documents and Settings\saltaf\My Documents\Visual Studio 2010\Projects\OnlineShoppingSystem\OnlineShoppingSiteAdminPanel\Temp\Images\untitled.bmp)
Have you tried checking the permissions for the folder which you are saving the file into? It's supposed to include the 'IIS_IUSRS' profile there (which should also have the WRITE permission to the target folder).
Hope this helps.

Trouble deleting a file from c:\windows\system32 using C#

Not quite sure why I can't get this file to delete. I'm logged in as Admin, tried "Run as Admin", tried running in the same folder, tried setting permissions on the file, tried creating a test 1.txt file to delete and no luck. It is acting like the file isn't there. I can see it in Windows Explorer. Please any help is welcome. Thank you for your time.
public void deleteFile(string FileToDelete)
{
//sets system32 to system32 path
string system32 = Environment.SystemDirectory + #"\";
//File.SetAttributes(#system32 + FileToDelete, FileAttributes.Normal);
try
{
//check if file exists
if (!File.Exists(#system32 + #FileToDelete))
{
//if it doesn't no need to delete it
Console.WriteLine("File doesn't exist or is has already been deleted.");
//Console.WriteLine(system32 + FileToDelete);
} //end if
//if it does, then delete
else
{
File.Delete(system32 + FileToDelete);
Console.WriteLine(FileToDelete + " has been deleted.");
} //end else
} //end try
//catch any exceptions
catch (Exception ex)
{
Console.WriteLine(Convert.ToString(ex));
} //end catch
} //end DeleteFile
I created a test file "test.txt" and it worked no problem. I should not that I didn't use the method you posted, but rather used the contents of your supplied method and used them within the main() method of a console application.
ou should also add ReadLine() to display any messages that are returned.
This is what I used, not that it's much different from what you supplied. If this code doesn't work for you then it must be a system privileged issue.
static void Main(string[] args)
{
string FileToDelete = "test.txt";
//sets system32 to system32 path
string system32 = Environment.SystemDirectory + #"\";
try
{
//check if file exists
if (!File.Exists(system32 + FileToDelete))
{
//if it doesn't no need to delete it
Console.WriteLine("File doesn't exist or is has already been deleted.");
//Console.WriteLine(system32 + FileToDelete);
Console.ReadLine();
} //end if
//if it does, then delete
else
{
File.Delete(system32 + FileToDelete);
Console.WriteLine(FileToDelete + " has been deleted.");
Console.ReadLine();
} //end else
} //end try
//catch any exceptions
catch (Exception ex)
{
Console.WriteLine(Convert.ToString(ex));
Console.ReadLine();
} //end catch
}
Try this one out
check if file exist on 64 bits system using File.Exists
If you're using Vista / Windows 7, maybe you're running into file virtualization issues. Have you tried adding a manifest with a <requestedExecutionLevel level="requireAdministrator"/> line in it ?

Categories