Exception in deleting image uploaded to the server in ASP.Net - asp.net

In asp.net, we have uploaded a .jpeg file and saved this as bitmap image using following code
HttpPostedFile uploadFile;
System.IO.Stream stream = uploadFile.InputStream;
using (System.Drawing.Image imgSource = System.Drawing.Bitmap.FromStream(stream))
{
System.Drawing.Image.GetThumbnailImageAbort myCallback = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
using (System.Drawing.Image imgThumbnail = imgSource.GetThumbnailImage(imgSource.Width, imgSource.Height, myCallback, IntPtr.Zero))
{
imgThumbnail.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg);
imgThumbnail.Dispose();
}
imgSource.Dispose();
}
stream.Close();
stream.Flush();
stream.Dispose();
After upload, if we perfrom delete operation it throws error.
We are following code to do so;
if (File.Exists(filePath))
{
File.Delete(filePath);
}
The exception says:The process cannot access the file 'abc.jpg' because it is being used by another process.
Does anyone know, why this is happening ?
Thanks in advance.

The garbage collector doesn't release it's resources to your file immediately.
You can try and run GC.Collect() to "force" the garbage collector to do it's thing. Do this after you have Disposed your file and before you try and delete it.
Edit: I you have some anti virus software on your machine it's likely that it is what is using your file. Same if you have an Explorer window open to the folder where the image is created etc.

How about trying first flushing and then closing the stream?

Also:
The using construct takes care of calling Dispose() for you. You don't need to do it explicitly, and in fact, doing so might break improperly implemented IDisposables.
Are you absolutely sure that filename is different each time? If not, concurrent requests may overwrite each others' files, so the exception you're getting may be caused by one thread trying to delete the file while another is overwriting it.

Related

Xamarin Open UWP Open file from "Documents" library

I have a Xamarin UWP app and am trying to load a file from my current users "Documents" library.
I understand that I need to add a File Type Association declaration first. I've done this and the file icon has changed to my application icon.
In the app I'm then using the FilePicker plugin from here...
https://github.com/ArtjomP/FilePicker-Plugin-for-Xamarin-and-Windows
FileData file = await CrossFilePicker.Current.PickFile();
Byte[] data = file.DataArray;
All I do is browse to the file and select it, but the application crashes with an access violation on the second line.
I've added the following capabilities to my UWP manifest, not sure if they are event relevant anymore.
<uap:Capability Name="documentsLibrary" />
<uap:Capability Name="removableStorage" />
How do I open my files? I ideally need to use a convenient location like the documents library.
Nick.
Edit:
I've followed this article, and still no joy.
https://www.pmichaels.net/2016/11/11/uwp-accessing-documents-library/
You are using a old package which most likely is no longer supported.
Try this one, https://github.com/jfversluis/FilePicker-Plugin-for-Xamarin-and-Windows
It is quite simple, and also supports UWP.
Sample usage
try
{
FileData fileData = await CrossFilePicker.Current.PickFile();
if (fileData == null)
return; // user canceled file picking
string fileName = fileData.FileName;
string contents = System.Text.Encoding.UTF8.GetString(fileData.DataArray);
System.Console.WriteLine("File name chosen: " + fileName);
System.Console.WriteLine("File data: " + contents);
}
catch (Exception ex)
{
System.Console.WriteLine("Exception choosing file: " + ex.ToString());
}
EDIT: I reworded the answer for clarity, and to avoid some implications that #MickyD rightly pointed in comments and I don't agree with those implications either:
This seems like a bug in the package as it doesn't work according to its documentation and one possible thing to do is to submit the issue to GitHub so that the bug is resolved by the developer of the package.
The other possible thing to do is to look for the alternatives. You may try to find other similar packages and see if they work, and the alternative for which I am sure that works is to use the native functions in System.Windows.Storage (as it is officially supported).

PDFsharp : How can i get rid of Adobe Reader when printing?

When I print a pdf file with PDFsharp in c# with this code below
printDocument1.PrinterSettings = printDialog1.PrinterSettings;
PdfFilePrinter.AdobeReaderPath = #"C:\Program Files\Adobe\Reader 10.0\Reader\AcroRd32.exe";
PdfFilePrinter printer = new PdfFilePrinter(pdfFilename, printDocument1.PrinterSettings.PrinterName);
try
{
printer.Print();
}
catch (Exception ex)
{
throw new NotImplementedException();
}
, everything is fine while printing but one thing I don't like is AdobeReader pops up.
How can I close this pop-up by code?
Please help.
The PdfFilePrinter class uses Process.Start to start Adobe Reader. You can play with the ProcessStartInfo options and maybe you can get the behavior you want (launch minimized or without a window at all etc.).
PDFsharp is open source and the PdfFilePrinter class is included in the source package. IIRC this class was developed in the days of Adobe Reader 5 or 6. Maybe Adobe Reader 10 or XI can do better with a slightly modified way of invoking them.
I don't have time to try this myself, but I would like to hear from you if you managed to improve your issue.
Or is the issue to close Adobe Reader after printing? That would be more difficult as you have to find out when Reader finished printing.

a generic error occurred in gdi+. while saving an image

Dear Expert i am getting an error while saving an image the code is as follows
ClsImageManager objImgManager = new ClsImageManager();
Bitmap ImageBitmap = objImgManager.GetBitmapFromBytes(ImageData);
Response.ContentType = "image/tiff";
ImageBitmap.Save(Response.OutputStream, ImageFormat.Tiff);
ImageBitmap.Dispose();
Response.End();
when i used Image.format.jpeg the code is working good but when i changes it to ImageFormat.Tiff then i am getting an error a generic error occurred in gdi+.
You should note that GDI/GDI+ (System.Drawing namespace) is not officially supported in ASP.NET - see "Caution" in http://msdn.microsoft.com/en-us/library/system.drawing.aspx.
WIC is supposed to be used instead GDI+ (see http://weblogs.asp.net/bleroy/archive/2009/12/10/resizing-images-from-the-server-using-wpf-wic-instead-of-gdi.aspx)
Said that, many had successfully use GDI+ in ASP.NET. Most probably, you should attempt saving image into memory stream (or on file) and then writing saved image into the response. See this link for details: http://www.west-wind.com/weblog/posts/2006/Oct/19/Common-Problems-with-rendering-Bitmaps-into-ASPNET-OutputStream
Another work-around can be related to user account. Apparently, GDI/GDI+ is bound to device context (screen, printer etc) and they may not be available under service accounts. So you may try running your ASP.NET code on some normal user account if that helps or not.
You may need to try explicitly encoding the image save.
Have a look at the code example at the bottom of this MSDN documentation on Image.Save
Image.Save Method (String, ImageCodecInfo, EncoderParameters)
The same actions can be applied to your save.
However, it could also possibly be that your objImgManager is disposing of the buffer where the image is stored before you can save it.
Bitmap ImageBitmap = objImgManager.GetBitmapFromBytes(ImageData);
You can get around this by creating a copy of the image by doing this:
Bitmap ImageBitmap = new Bitmap(objImgManager.GetBitmapFromBytes(ImageData));

is it an issue of moving/renaming a folder of asp.net?

I would like to rename a folder with asp.net:
string oldFolderTitlePath = ServerPhyscialPath + oldFolderTitle + "/";
string newFolderTiltePath = ServerPhyscialPath + newFolderTille+ "/";
DirectoryInfo diPath = new DirectoryInfo(oldFolderTitlePath);
if(diPath.Exists)
{
///Now move(Rename) folder on the server
Directory.Move(oldFolderTitlePath, newFolderTiltePath);
}
I wonder that if the old folder contains number of files and the size is more than 1GB. Will it take a lot of time to rename a folder on asp.net?
Thanks in advance.
Generally, no it should not take a lot of time. You're basically changing the name of the directory not actually moving its contents on the disk.
That said, I'd be very careful with doing what you're doing. I'm always wary of IO operations from ASP.NET -- the reason: Many users could potentially be executing this code at the same time. That could lead to all sorts of problems. You need to make sure this operation is thread safe (perhaps by locking a static variable).
http://msdn.microsoft.com/en-us/library/c5kehkcz%28v=vs.71%29.aspx
http://msdn.microsoft.com/en-us/library/system.io.directory.move.aspx

How to efficiently scale and crop images in an ASP.NET app?

We're having problems with an ASP.NET application which allows users to upload, and crop images. The images are all scaled to fixed sizes afterwards. We basically run out of memory when a large file is processed; it seems that the handling of JPEG is rather inefficient -- we're using System.Drawing.BitMap. Do you have any general advice, and perhaps some pointers to a more efficient image handling library? What experiences do you have?
I had the same problem, the solution was to use System.Drawing.Graphics to do the transformations and dispose every bitmap object as soon as I was finished with it. Here's a sample from my library (resizing) :
public Bitmap ApplyTo(Bitmap bitmap)
{
using (bitmap)
{
Bitmap newBitmap = new Bitmap(bitmap, CalculateNewSize(bitmap));
using (Graphics graphics = Graphics.FromImage(newBitmap))
{
graphics.SmoothingMode =
SmoothingMode.None;
graphics.InterpolationMode =
InterpolationMode.HighQualityBicubic;
graphics.CompositingQuality =
CompositingQuality.HighQuality;
graphics.DrawImage(
bitmap,
new Rectangle(0, 0, newBitmap.Width, newBitmap.Height));
}
return newBitmap;
}
}
I found imageresizer and its great. and good API. Works Great.
Downloaded from Visual studio 2010 Extension Manager: http://nuget.org/.
Easy Steps to download API in VS-2010:
1). Install Extension http://nuget.org/.
3). Find and Install ImageResizing
4).Then Code: (I m using here cropping. you can use any) Documentation on imageresizing.net
string uploadFolder = Server.MapPath(Request.ApplicationPath + "images/");
FileUpload1.SaveAs(uploadFolder + FileUpload1.FileName);
//The resizing settings can specify any of 30 commands.. See http://imageresizing.net for details.
ResizeSettings resizeCropSettings = new ResizeSettings("width=200&height=200&format=jpg&crop=auto");
//Generate a filename (GUIDs are safest).
string fileName = Path.Combine(uploadFolder, System.Guid.NewGuid().ToString());
//Let the image builder add the correct extension based on the output file type (which may differ).
fileName = ImageBuilder.Current.Build(uploadFolder + FileUpload1.FileName, fileName, resizeCropSettings, false, true);
Try!!! its very awsumm and easy to use. thanks.
A couple of thoughts spring to mind -
What size of images do you allow
your users to upload and can you
impose restrictions on this?
When you're using the
System.Drawing.Bitmap class, are you
remembering to dispose of it
correctly? We found one of the primary causes of System.OutOfMemoryException exceptions on our shared hosting platform was users not disposing of Bitmap objects correctly.
Kev
There was an older bug with .net that all images would default to 32 bits per pixel - at this size you can exhaust your memory pretty fast. Please use PixelFormat structure to make sure this is not the case for your problem.
This link might help: http://msdn.microsoft.com/en-us/library/aa479306.aspx
Do you perhaps have a stack trace to look at?
I have also done some image editing after a user has uploaded an image. The only problems that I ran into were restrictions on file upload size on the browsers and timeouts. But nothing related to .Net's libraries.
Something else to consider. If you are doing multiple images or have some dangerous looping somewhere then are you making sure to flush() and dispose() things.

Resources