Web Application not able to Delete files for Read/Write Enabled Folders in ASP.NET - asp.net

When I'm trying to delete the images uploaded by me via website named "SampleApplication" I can see the following error shown in Stack Trace
The process cannot access the file 'D:\Hosting\123456\html\App_Images\myfolder1\eKuK2511.png' because it is being used by another process.
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.IO.IOException: The process cannot access the file 'D:\Hosting\123456\html\App_Images\myfolder1\eKuK2511.png' because it is being used by another process.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[IOException: The process cannot access the file 'D:\Hosting\123456\html\App_Images\myfolder1\eKuK2511.png' because it is being used by another process.]
System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) +9723350
System.IO.File.Delete(String path) +9545728
SampleApplication.BasePage.DeleteApp_ImagesById(DataTable dt) +503
SampleApplication.PostLease.MyAccount.DeleteAd_Property(Object sender, EventArgs e) +193
System.Web.UI.WebControls.LinkButton.OnClick(EventArgs e) +118
System.Web.UI.WebControls.LinkButton.RaisePostBackEvent(String eventArgument) +113
System.Web.UI.WebControls.LinkButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +9
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +176
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +5563
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.272
The folder App_Images has been given Read/write Permission and inherits to child folders namely myfolder1, myfolder2, myfolder3, myfolder4. Even when I tried to forcefully delete the image eKuK2511.png from the FTP File manager it is showing the following error:
550 The process cannot access the file because it is being used by another process.
How to getrid of this error?
Edit:
Upload Code:
public void UploadImages()
{
if (ServerSideValidation() == true)
{
string SavePath;
ImgPaths = new List<string>();
// Get the HttpFileCollection
HttpFileCollection hfc = Request.Files;
if (hfc.Count > 0)
{
for (int i = 0; i < hfc.Count; i++)
{
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength > 0)
{
#region trials compression.
SavePath = "~/App_Images/" + Session["AppContext"].ToString() + "/" + GetUniqueKey() + GetFileExtension(hpf.FileName);
SaveImageByCompressing(hpf, SavePath);
#endregion
//SavePath can be saved in DB.
ImgPaths.Add(SavePath);
//Save Thumbnail Image.
if (i == 0)
{
string savedName = "Thumb_" + GetUniqueKey() + GetFileExtension(AppDomain.CurrentDomain.BaseDirectory + ImgPaths[0].ToString().Replace("~/", "\\").Replace("/", "\\"));
SavePath = "~/App_Images/" + Session["AppContext"].ToString() + "/" + savedName;
SaveThumbImage(AppDomain.CurrentDomain.BaseDirectory + ImgPaths[0].ToString().Replace("~/", "").Replace("/", "\\"), AppDomain.CurrentDomain.BaseDirectory + "App_Images\\" + Session["AppContext"].ToString() + "\\" + savedName, 75, 75);
ImgPaths.Add(SavePath);
}
}
}
Session.Remove("AppContext");
lblMsg.Text = "Images Uploaded Successfully.";
//ShowUploadedImages(ImgPaths);
}
else
{
lblMsg.Text = "Images uploaded are either in wrong format or were deleted after uploading.";
}
}
else
{
lstPaths = new List<string>();
lblMsg.Text = "No Images Uploaded";
}
}
private void SaveImageByCompressing(HttpPostedFile hpf, string filePath)
{
Image imgFromClient = Image.FromStream(hpf.InputStream);
string SavetoFullPath = AppDomain.CurrentDomain.BaseDirectory + filePath.Replace("~/", "").Replace("/", "\\");
Image.GetThumbnailImageAbort myCallbackCompressed = new Image.GetThumbnailImageAbort(ThumbnailCallback);
Image imageToSave= imgFromClient.GetThumbnailImage(imgFromClient.Width, imgFromClient.Height, myCallbackCompressed, IntPtr.Zero);
imageToSave.Save(SavetoFullPath, System.Drawing.Imaging.ImageFormat.Jpeg);
}
public static void SaveThumbImage(string imagePath, string filePath, int width = 0, int height = 0)
{
Image originalImage = Image.FromFile(imagePath);
if (width > 0 && height > 0)
{
Image.GetThumbnailImageAbort myCallback = new Image.GetThumbnailImageAbort(ThumbnailCallback);
Image imageToSave = originalImage.GetThumbnailImage(width, height, myCallback, IntPtr.Zero);
imageToSave.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg);
}
else
{
originalImage.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
private static bool ThumbnailCallback() { return false; }
private bool ServerSideValidation()
{
string errorMsg = string.Empty, temp = null;
bool errorFlag = true;
// Get the HttpFileCollection
HttpFileCollection hfc = Request.Files;
for (int i = 0; i < hfc.Count; i++)
{
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength > 0 && hpf.FileName!=String.Empty)
{
temp = ValidateImage(hpf);
if (temp != null)
{
errorMsg += GetFileName(hpf.FileName.ToString()) + " has error : " + temp;
temp = null;
}
}
else
{
return false;
}
}
if (!string.IsNullOrWhiteSpace(errorMsg))
{
lblMsg.Text = errorMsg;
errorFlag = false;
}
return errorFlag;
}
private string GetFileExtension(string filePath)
{
FileInfo fi = new FileInfo(filePath);
return fi.Extension;
}
private string GetFileName(string filePath)
{
FileInfo fi = new FileInfo(filePath);
return fi.Name;
}
private string GetUniqueKey()
{
int maxSize = 8;
char[] chars = new char[62];
string a = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
chars = a.ToCharArray();
int size = maxSize;
byte[] data = new byte[1];
RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();
crypto.GetNonZeroBytes(data);
size = maxSize;
data = new byte[size];
crypto.GetNonZeroBytes(data);
StringBuilder result = new StringBuilder(size);
foreach (byte b in data)
{
result.Append(chars[b % (chars.Length - 1)]);
}
return Session["AppContext"].ToString() + Page.User.Identity.Name.ToString() + result.ToString();
}
private string ValidateImage(HttpPostedFile myFile)
{
string msg = null;
//6MB
int FileMaxSize = 6291456;
//Check Length of File is Valid or Not.
if (myFile.ContentLength > FileMaxSize)
{
msg = msg + "File Size is Too Large. You are allowed only a maximum of 6MB per Image.";
}
//Check File Type is Valid or Not.
if (!IsValidFile(myFile.FileName))
{
msg = msg + "Invalid File Type.";
}
return msg;
}
private bool IsValidFile(string filePath)
{
bool isValid = false;
string[] fileExtensions = { ".BMP", ".JPG", ".PNG", ".GIF", ".JPEG" };
for (int i = 0; i < fileExtensions.Length; i++)
{
if (filePath.ToUpper().Contains(fileExtensions[i]))
{
isValid = true; break;
}
}
return isValid;
}
Delete Code:
/// <summary>
/// Delete all images. If there are no Images then by default NoImage.png is assigned. So skip deleting that image.
/// </summary>
/// <param name="dt"></param>
protected void DeleteApp_ImagesById(DataTable dt)
{
if (dt.Rows[0][0].ToString() != "~/images/NoImage.png")
{
for (int i = 0; i < dt.Columns.Count; i++)
{
if (dt.Rows[0][i].ToString() != string.Empty)
{
string str = Regex.Replace(dt.Rows[0][i].ToString(), "~/", "");
File.Delete(Request.PhysicalApplicationPath.ToString() + Regex.Replace(str, "/", "\\").ToString());
}
}
}
}

The docs on MSDN about Image.Save say that the file remains locked until the Image is disposed.
So I suppose that changing the code that save the images in this way
private void SaveImageByCompressing(HttpPostedFile hpf, string filePath)
{
using(Image imgFromClient = Image.FromStream(hpf.InputStream))
{
string SavetoFullPath = AppDomain.CurrentDomain.BaseDirectory +
filePath.Replace("~/", "").Replace("/", "\\");
Image.GetThumbnailImageAbort myCallbackCompressed =
new Image.GetThumbnailImageAbort(ThumbnailCallback);
using(Image imageToSave= imgFromClient.GetThumbnailImage(imgFromClient.Width,
imgFromClient.Height, myCallbackCompressed, IntPtr.Zero))
{
imageToSave.Save(SavetoFullPath, System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
}
public static void SaveThumbImage(string imagePath, string filePath,
int width = 0, int height = 0)
{
using(Image originalImage = Image.FromFile(imagePath))
{
if (width > 0 && height > 0)
{
Image.GetThumbnailImageAbort myCallback =
new Image.GetThumbnailImageAbort(ThumbnailCallback);
using(Image imageToSave = originalImage.GetThumbnailImage(width, height,
myCallback, IntPtr.Zero))
{
imageToSave.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
else
{
originalImage.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
}
is a safe way to ensure your images are immediately unlocked when you finish with the upload code

Related

how can i upload file to server in asp.net

I have 2 pages send.aspx and recive.aspx.
In send.aspx, I have FileUpload and Button that send selected file to recive.aspx page.
In below you can see recive.aspx.cs code in Page_Load
at the end .
How can I send file to this page?
protected void Page_Load(object sender, EventArgs e)
{
string action = Request.Params["action"];
if (action == null)
{
Response.StatusCode = 400;
Response.End();
}
if (action.Equals("upload"))
{
HttpPostedFile file = Request.Files["file"];
if (file != null && file.ContentLength > 0)
{
//string guid = Guid.NewGuid().ToString();
string ext = Path.GetExtension(file.FileName);
//2- Get and check file extension
string[] validExtesions = { ".e", ".jpg", ".gif", ".png", ".rar",
".zip",".3gp",".3gpp",".mp4",".mov",".wmv",".avi", "",".jpeg", ".mp3", ".ogg"};
if (Array.IndexOf(validExtesions, ext.ToLower()) < 0)
{
Response.Write("Invalid file extension!");
Response.End();
}
//3- Get and check file size
long fileSize = file.ContentLength;
fileSize /= 1024;
if (fileSize > 2048000)
{
Response.Write("Fiele size must be < 2GB");
Response.End();
}
//4- Get file name
string fileName = Path.GetFileName(file.FileName);
//5- Check file exist and if (true) generate new name
while (File.Exists(Path.Combine(UploadFolder, fileName)))
fileName = "1" + fileName;
string fname = fileName;
string path = Server.MapPath(Path.Combine(UploadFolder, fname));
file.SaveAs(path);
Response.Write(fname);
Response.End();
}
else
{
Response.StatusCode = 400;
Response.End();
}
}
}

Handle file name duplication when creating files in alfresco

I have a Java-backed webscript in repo tier that creates files (with given name) in a given folder in Alfresco.
To handle the file name duplication issue I wrote this code:
NodeRef node = null;
try {
node = createNode(fullName, folderNodeRefId);
} catch (DuplicateChildNodeNameException e) {
System.out.println("Catched");
boolean done = false;
for (int i = 1; !done; i++) {
String newName = filename + "_" + i + "." + fileFormat;
System.out.println("Duplicate Name. Trying: " + newName);
try {
node = createNode(newName, folderNodeRefId);
done = true;
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
System.out.println("Done");
ContentWriter writer = serviceRegistry.getContentService().getWriter(node, ContentModel.PROP_CONTENT, true);
writer.setMimetype(getFileFormatMimetype(fileFormat));
writer.putContent(inputStream);
writer.guessEncoding();
and
private NodeRef createNode(String filename, String folderNodeRefId)
throws InvalidNodeRefException, InvalidTypeException, InvalidQNameException {
System.out.println("In " + filename);
NodeRef folderNodeRef = new NodeRef(folderNodeRefId);
Map<QName, Serializable> props = new HashMap<QName, Serializable>(1);
props.put(ContentModel.PROP_NAME, filename);
return serviceRegistry.getNodeService()
.createNode(folderNodeRef, ContentModel.ASSOC_CONTAINS,
QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, filename), ContentModel.TYPE_CONTENT,
props)
.getChildRef();
}
The codes work very fine if there is no file name duplication (a new name). But it does nothing when there is a duplication, although it executes without any errors! When I test it it doesn't throw any exceptions but no file is created either!
Any hints about the cause of that?
Thanks,
I tested this code , It's working fine
#Test
public void createNode() {
AuthenticationUtil.setFullyAuthenticatedUser(ADMIN_USER_NAME);
NodeRef node = null;
String fileFormat = "txt";
String filename = "test";
NodeRef folderNodeRef = getCompanyHome();
//Create first node
node = createNode(filename, folderNodeRef);
try {
node = createNode(filename, folderNodeRef);
} catch (DuplicateChildNodeNameException e) {
System.out.println("Catched");
boolean done = false;
for (int i = 1; !done; i++) {
String newName = filename + "_" + i + "." + fileFormat;
System.out.println("Duplicate Name. Trying: " + newName);
try {
node = createNode(newName, folderNodeRef);
done = true;
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
System.out.println("Done");
}
private NodeRef getCompanyHome() {
return nodeLocatorService.getNode("companyhome", null, null);
}
private NodeRef createNode(String filename, NodeRef folderNodeRef) throws InvalidNodeRefException, InvalidTypeException, InvalidQNameException {
System.out.println("In " + filename);
Map<QName, Serializable> props = new HashMap<QName, Serializable>(1);
props.put(ContentModel.PROP_NAME, filename);
return serviceRegistry.getNodeService().createNode(folderNodeRef, ContentModel.ASSOC_CONTAINS,
QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, filename), ContentModel.TYPE_CONTENT,props).getChildRef();
}

File Upload is not working in asp.net

I'm trying to upload a file using FileUpload, and it doesn't work. After I click the button, it reloads the page, but the image is not saved
Below code is from microsoft, but still not working
protected void uploadBtn_Click(object sender, EventArgs e)
{
Boolean fileOK = false;
String path = Server.MapPath("~/Sources/images/");
if (imageUpload.HasFile)
{
String fileExtension =
System.IO.Path.GetExtension(imageUpload.FileName).ToLower();
String[] allowedExtensions = { ".gif", ".png", ".jpeg", ".jpg" };
for (int i = 0; i < allowedExtensions.Length; i++)
{
if (fileExtension == allowedExtensions[i])
{
fileOK = true;
}
}
}
if (fileOK)
{
try
{
imageUpload.PostedFile.SaveAs(path
+ imageUpload.FileName);
statusUploadLbl.Text = "File uploaded!";
}
catch (Exception ex)
{
statusUploadLbl.Text = "File could not be uploaded.";
}
}
else
{
statusUploadLbl.Text = "Cannot accept files of this type.";
}
}
Please help, thanks

Error reading words in the text file

I have been working on a code snippet today . A part of the Code reads the number of words in the file.I am using StreamReader to do the same , but it seems to give DirectoryNotFound Exception.Here is the code for the event
protected void Button1_Click(object sender, EventArgs e)
{
string filename = string.Empty;
string FilePath = ConfigurationManager.AppSettings["FilePath"].ToString();
if (FileUpload1.HasFile)
{
string[] Exe = { ".txt" };
string FileExt = System.IO.Path.GetExtension(FileUpload1.PostedFile.FileName);
bool isValidFile = Exe.Contains(FileExt);
if (isValidFile)
{
int FileSize = FileUpload1.PostedFile.ContentLength;
if (FileSize <= 102400)
{
filename = Path.GetFileName(FileUpload1.FileName);
FileUpload1.SaveAs(Server.MapPath(FilePath) + filename);
StreamReader sr = new StreamReader(FilePath+filename);
//The error shows up here and i have tried to use FilePath as the single parameter too
int counter = 0;
string delim = " ,.?!";
string[] fields = null;
string line = null;
while (!sr.EndOfStream)
{
line = sr.ReadLine();//each time you read a line you should split it into the words
line.Trim();
fields = line.Split(delim.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
counter += fields.Length; //and just add how many of them there is
}
sr.Close();
lblcount.Text = counter.ToString();
lblMsg.Text = "File upload successfully!";
}
else
{
lblMsg.Text = "File Size allowed upto 100kb!";
}
}
else
{
lblMsg.Text = "Please Upload a text File!";
}
}
else
{
lblMsg.Text = "Please upload a file!";
}
}
}
Can this be sorted out ??
Thanks in Advance!
Use Path.Combine to build paths:
string path = Path.Combine(Server.MapPath(FilePath), filename);
FileUpload1.SaveAs(path);
using(StreamReader sr = new StreamReader(path))
{
// ...
}

wait() in asp.net (showing uploaded image)

I want to force my program to wait some moments after doing something, and then do somwthing else, in asp.net and silverlight.
(In Detail, I want to upload an image by silverlight program, and then show it in my page by an Image control. But when I upload images which their size is about 6KB or upper, the image doesn't show, however it has been uplaoded successfully. I think that waiting some moments may solve the problem)
May anyone guide me?
thank you
I use the code in this page
This is the code in MyPage.Xaml:
private void UploadBtn_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Multiselect = false;
dlg.Filter = UPLOAD_DIALOG_FILTER;
if ((bool)dlg.ShowDialog())
{
progressBar.Visibility = Visibility.Visible;
progressBar.Value = 0;
_fileName = dlg.File.Name;
UploadFile(_fileName, dlg.File.OpenRead());
}
else
{
//user clicked cancel
}
}
private void UploadFile(string fileName, Stream data)
{
// Just kept here
progressBar.Maximum = data.Length;
UriBuilder ub = new UriBuilder("http://mysite.com/receiver.ashx");
ub.Query = string.Format("fileName={0}", fileName);
WebClient c = new WebClient();
c.OpenWriteCompleted += (sender, e) =>
{
PushData(data, e.Result);
e.Result.Close();
data.Close();
};
try
{
c.OpenWriteAsync(ub.Uri);
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
private void PushData(Stream input, Stream output)
{
byte[] buffer = new byte[input.Length];
int bytesRead;
while ((bytesRead = input.Read(buffer, 0, buffer.Length)) != 0)
{
output.Write(buffer, 0, buffer.Length);
}
progressBar.Value += input.Length;
if (progressBar.Value >= progressBar.Maximum)
{
progressBar.Visibility = System.Windows.Visibility.Collapsed;
loadImage();
}
}
private void loadImage()
{
Uri ur = new Uri("http://mysite.com/upload/" + _fileName);
img1.Source = new BitmapImage(ur);
}
And this is receiver.ashx:
public void ProcessRequest(HttpContext context)
{
string filename = context.Request.QueryString["filename"].ToString(); using (FileStream fs = File.Create(context.Server.MapPath("~/upload/" + filename)))
{
SaveFile(context.Request.InputStream, fs);
}
}
private void SaveFile(Stream stream, FileStream fs)
{
byte[] buffer = new byte[stream.Length];
int bytesRead;
while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0)
{
fs.Write(buffer, 0, bytesRead);
}
}

Resources