I keep on getting the same error in uploading a image on the published project in IIS: "UnauthorizedAccessException: Access to the path 'C:\inetpub\wwwroot\TestProj\wwwroot\files\clients\1111_64d96158-2a74-4277-98ed-7b12ba290b2d_CJQYABUT-SAMPLE-ID.jpg' is denied."
I keep on chaging the codes from _webHostEnvironment.WebRootPath and ContentRootPath, i tried using var uniqueFileName = "wwwroot/files/clients/"; and still dont work.
Here are some of the codes i tried,
string uniqueFileName = null;
if (client.FirstFile != null)
{
string uploadsFolder ="wwwroot/files/clients/";
uniqueFileName = client.Number + "_" + Guid.NewGuid().ToString() + "_" + client.FirstFile.FileName;
string filePath = Path.Combine(uploadsFolder, uniqueFileName);
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
await client.FirstFile.CopyToAsync(fileStream);
}
client.FilePath = "/files/UploadImages/" + uniqueFileName;
}
string uniqueFileName = null;
if (client.FirstFile != null)
{
string uploadsFolder = Path.Combine(_webHostEnvironment.WebRootPath, "files/clients/");
uniqueFileName = client.Number + "_" + Guid.NewGuid().ToString() + "_" + client.FirstFile.FileName;
string filePath = Path.Combine(uploadsFolder, uniqueFileName);
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
await client.FirstFile.CopyToAsync(fileStream);
}
client.FilePath = "/files/UploadImages/" + uniqueFileName;
}
string uniqueFileName = null;
if (client.FirstFile != null)
{
string uploadsFolder = Path.Combine(_webHostEnvironment.ContentRootPath, "wwwroot/files/clients/");
uniqueFileName = client.Number + "_" + Guid.NewGuid().ToString() + "_" + client.FirstFile.FileName;
string filePath = Path.Combine(uploadsFolder, uniqueFileName);
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
await client.FirstFile.CopyToAsync(fileStream);
}
client.FilePath = "/files/UploadImages/" + uniqueFileName;
}
I don't know if I'm missing something, please help. Thanks
The "UnauthorizedAccessException" error message you're seeing is indicating that the user account that the IIS worker process is running under does not have permission to access the specified file path.
There are a few things you can try to resolve this issue:
Make sure that the user account that the IIS worker process is running under (usually "IIS_IUSRS") has read and write access to the folder that you're trying to save the image in.
If you are using a version of IIS less than 8.5, you may need to configure the application pool to run as the "LocalSystem" account, which has the necessary permissions to access the folder.
You can also try to give the permissions for the folder to the "Everyone" group to confirm it's not a permission issue. But keep in mind that giving permissions to the "Everyone" group could be a security risk.
If you're still facing the same issue, you could try checking the file and folder permissions for the folder in Windows.
Another alternative is change the location of the image to be stored, to a folder outside the IIS.
Make sure that after you've made any changes to the file or folder permissions, you restart the IIS worker process for the changes to take effect.
Related
I am able to move an object in an S3 bucket from one directory to another directory using C# but unable to copy all current permissions with that object.
For example, my current object has public access permissions but after moving it to another directory it lost the public read permissions.
Here is the code I'm using to move objects:
public void MoveFile(string sourceBucket, string destinationFolder, string file) {
AmazonS3Client s3Client = new AmazonS3Client(ConfigurationHelper.AmazonS3AccessKey, ConfigurationHelper.AmazonS3SecretAccessKey, Amazon.RegionEndpoint.USEast1);
S3FileInfo currentObject = new S3FileInfo(s3Client, sourceBucket, file);
currentObject.MoveTo(sourceBucket + "/" + destinationFolder, file);
}
Here is the output after moving file to another directory:
It lost public "Read" permission.
I've figure out issue myself, by using CopyObject() and DeleteObject() instead of using moveTo inbuild method and that solves my issue,
here is the code which really helped me:
CopyObjectRequest copyObjectRequest = new CopyObjectRequest
{
SourceBucket = sourceBucket,
DestinationBucket = sourceBucket + "/" + destinationFolder,
SourceKey = file,
DestinationKey = file,
CannedACL = S3CannedACL.PublicRead,
StorageClass = S3StorageClass.StandardInfrequentAccess,
};
CopyObjectResponse response1 = s3Client.CopyObject(copyObjectRequest);
var deleteObjectRequest = new DeleteObjectRequest
{
BucketName = sourceBucket,
Key = file
};
s3Client.DeleteObject(deleteObjectRequest);
I'm posting answer so it can be helpful for someone!!!
I am trying to write byte array to a file and sending it as email. After that I need to delete the file from the saved location.
But while deleting, it throws the error
'The process cannot access the file 'file path' because it is being
used by another process.'
As per the File.WriteAllBytes() documentation, it Creates a new file, writes the specified byte array to the file, and then closes the file. If the target file already exists, it is overwritten. Pls help me to find a solution.
string FolderPath = MyPath + "PaySlips";
string filePath = FolderPath + "/" + userID + "-PaySlip_" + ddlMonth.SelectedItem.Text + "_" + ddlYear.SelectedItem.Text + ".pdf";
if (!Directory.Exists(FolderPath))
{
Directory.CreateDirectory(FolderPath);
}
File.WriteAllBytes(filePath, bytes);
ArrayList attachments = new ArrayList();
attachments.Add(filePath);
SendEmail(emailID, cc, attachments);
if (File.Exists(attachments[0].ToString())) {
File.Delete(attachments[0].ToString()); //exception happens here
}
'''
string FolderPath = MyPath + "PaySlips";
string filePath = FolderPath + "/" + userID + "-PaySlip_" + ddlMonth.SelectedItem.Text + "_" + ddlYear.SelectedItem.Text + ".pdf";
if (!Directory.Exists(FolderPath))
{
Directory.CreateDirectory(FolderPath);
}
File.WriteAllBytes(filePath, bytes);
File.Close();
File.Dispose();
ArrayList attachments = new ArrayList();
attachments.Add(filePath);
SendEmail(emailID, cc, attachments);
if (File.Exists(attachments[0].ToString())) {
File.Delete(attachments[0].ToString());
}
I got the solution. Thanks #Cleptus
File.WriteAllBytes() is already closed and in the SendMail(), it's got opened again. So by disposing those objects, it worked
The SendEmail() method in my code has
SmtpClient smC= new SmtpClient();
MailMessage mM= new MailMessage();
I added dispose of SMTPClient and MailMessage in finally block
try
{
smC.Send(mM);
}
catch (Exception ex)
{
Err = ex.Message;
}
finally {
mM.Dispose();
smC.Dispose();
}
you need to delete the file after "close" not before. As long as the close has not executed, the file will be in the stream loop and it counts as its own process and thus cannot be deleted until the file is closed. Hope this helps. Im guessing your close statement is below that code. Move it before the delete statment.
I' try to upload file from .net core application, it is working fine with windows OS,
but when i try to run a.net core application in ubuntu OS,
In this while uploading file in perticular folder, application add its root path automatically.
Here is my code as bellow
var Image = editProfile.PostedFile;
if (Image != null)
{
var Extension = Path.GetExtension(Image.FileName);
var FileName = DateTime.Now.Ticks + Extension;
var SaveFileName = Settings.UserProfilePhotoPath + FileName;
var FilePath = Settings.DisplayCompanyLogo() + "/" + FileName;
using (var fileStream = new FileStream(FilePath, FileMode.Create))
{
await Image.CopyToAsync(fileStream);
}
editProfile.CompanyLogo = SaveFileName;
}
else
{
editProfile.CompanyLogo = null;
}
I am trying to download a file usng FTP within a C# console application, but even though I now the paths are correct I always get an error saying "550 file not found".
Is there any way, to return the current path (once connected to the server)?
// lade datei von FTP server
string ftpfullpath = "ftp://" + Properties.Settings.Default.FTP_Server + Properties.Settings.Default.FTP_Pfad + "/" + Properties.Settings.Default.FTP_Dateiname;
Console.WriteLine("Starte Download von: " + ftpfullpath);
using (WebClient request = new WebClient())
{
request.Credentials = new NetworkCredential(Properties.Settings.Default.FTP_User, Properties.Settings.Default.FTP_Passwort);
byte[] fileData = request.DownloadData(ftpfullpath);
using (FileStream file = File.Create(#path + "/tmp/" + Properties.Settings.Default.FTP_Dateiname))
{
file.Write(fileData, 0, fileData.Length);
file.Close();
}
Console.WriteLine("Download abgeschlossen!");
}
EDIT
My mistake. Fixed the filepath, still getting the same error. But if I connect with FileZilla that's the exact file path.
Finally found a solution by using System.Net.FtpClient (https://netftp.codeplex.com/releases/view/95632) and using the following code.
// aktueller pfad
string apppath = Directory.GetCurrentDirectory();
Console.WriteLine("Bereite Download von FTP Server vor!");
using (var ftpClient = new FtpClient())
{
ftpClient.Host = Properties.Settings.Default.FTP_Server;
ftpClient.Credentials = new NetworkCredential(Properties.Settings.Default.FTP_User, Properties.Settings.Default.FTP_Passwort);
var destinationDirectory = apppath + "\\Input";
ftpClient.Connect();
var destinationPath = string.Format(#"{0}\{1}", destinationDirectory, Properties.Settings.Default.FTP_Dateiname);
Console.WriteLine("Starte Download von " + Properties.Settings.Default.FTP_Dateiname + " nach " + destinationPath);
using (var ftpStream = ftpClient.OpenRead(Properties.Settings.Default.FTP_Pfad + "/" + Properties.Settings.Default.FTP_Dateiname))
using (var fileStream = File.Create(destinationPath , (int)ftpStream.Length))
{
var buffer = new byte[8 * 1024];
int count;
while ((count = ftpStream.Read(buffer, 0, buffer.Length)) > 0)
{
fileStream.Write(buffer, 0, count);
}
}
}
I think your filename is wrong. Your first line writes a different name than what you set to ftpfullpath. You us FTP_Dateiname on the first line but FTP_Pfad when you set ftpfullpath.
To see what's actually happening move your first line after 'string ftpfullpath...')
and change it to Console.WriteLine("Starte Download von: " + ftpfullpath);
After I created a file in a directory the directory is locked as long as my program which created the file is running. Is there any way to release the lock? I need to rename the directory couple of lines later and I always get an IOException saying "Access to the path "..." denied".
Directory.CreateDirectory(dstPath);
File.Copy(srcPath + "\\File1.txt", dstPath + "\\File1.txt"); // no lock yet
File.Create(dstPath + "\\" + "File2.txt"); // causes lock
File.Create(string path) Creates a file and leaves the stream open.
you need to do the following:
Directory.CreateDirectory(dstPath);
File.Copy(srcPath + "\\File1.txt", dstPath + "\\File1.txt");
using (var stream = File.Create(dstPath + "\\" + "File2.txt"))
{
//you can write to the file here
}
The using statement asures you that the stream will be closed and the lock to the file will be released.
Hope this helps
Have you tried closing your FileStream? e.g.
var fs = File.Create(dstPath + "\\" + "File2.txt"); // causes lock
fs.Close();
i suggest you use a using statement:
using (var stream = File.Create(path))
{
//....
}
but you should also be aware of using object initializers in using statements:
using (var stream = new FileStream(path) {Position = position})
{
//....
}
in this case it will be compiled in:
var tmp = new FileStream(path);
tmp.Position = position;
var stream = tmp;
try
{ }
finally
{
if (stream != null)
((IDisposable)stream).Dispose();
}
and if the Position setter throw exception, Dispose() will not being called for the temporary variable.