Loading and checking image from local disk in C# - c#

i'm trying to load image from local disk, and it's working. But my problem is that i'd like to check if image is available in folder, and if not - then MessageBox.Show("No image!");
Loading image:
Bitmap bitmap1 = new Bitmap(#"Documentation\\Pictures\\"+table[8]+".jpg");
pictureBox.Image=bitmap1;

You could use the File.Exists method to check whether a given file exists:
var file = Path.ChangeExtension(table[8], ".jpg");
var fullPath = Path.Combine(#"Documentation\Pictures", file);
if (!File.Exists(fullPath))
{
MessageBox.Show("No image!");
}
else
{
pictureBox.Image = new Bitmap(fullPath);
}

Try using the File.Exists method for testing if the file itself exists.
Note, however, that between invoking that method and invoking the method which actually loads the file, the file could already be gone. Thus, exception handling should be used nonetheless.
See this link for further info.

Try this
string fileName = string.Format(#"Documentation\\Pictures\\{0}.jpg",table[8]);
if(!File.Exists(fileName))
{
MessageBox.Show("No Image");
}
else
{
Picture1.Image = Image.FromFile(fileName);
}

Related

BitmapFrame.Create fails with escaped characters in Uri

I am using WPF/C# in VS2017.
My code takes a path to an image file as a string and tries to load it into a BitmapFrame, which has worked fine mostly, except someone tested it with some image files from a Mac and it threw an exception. It turns out that the filename contains the character #F025, which in Windows is just displayed as a thick dot.
The files are photos, named from the photograph title. This one had a question mark in it, but ended up with #F025.
Anyway, the code converts the string to a Uri and then uses BitmapFrame as follows:
public new void Init()
{
Source = new Uri(Path);
fi = new FileInfo(Path);
BitmapImage bs;
try
{
Image = BitmapFrame.Create(Source);
Metadata = new ExifMetadata(Image);
}
catch (Exception e)
{
Error = e.Message;
IsBroken = true;
}
When I look at the Uri "Source" in the debugger, then #F025 character has been replaced with "%25EF%2580%25A5". The Create function throws a "File Not Found" exception.
If there any way of converting this to a Uri that the Create function will accept, or perhaps just using the string Path to load it instead? I did try using a stream with the filename but that didn't work either.
TIA.
You may try to create the BitmapFrame from a FileStream. Note that BitmapCacheOption.OnLoad must be set in order to be able to close the stream immediately after the Create call.
using (var stream = File.OpenRead(Path))
{
Image = BitmapFrame.Create(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
}

Delete existing Image before create new Image

Hi i have the following Function:
private void CreateRoomImage(string path)
{
Directory.CreateDirectory(path);
var file = "";
foreach (PanelView panelView in pv)
{
var RoomImage = GetRaumImageName(panelView.Title);
file = path + GetImageFile(RoomImage);
if (File.Exists(file))
{
File.Delete(file);
}
using (var img = GetRaumImage(panelView.Title, panelView))
{
ImageWriter imgWriter = new ImageWriter(ImageFormat.Bmp);
imgWriter.Save(img, file);
}
}
}
My Problem is that everytime i try to Delete the existing File my programm is throwing an exception:
The process can not access the file because it is being used by another process
Is there a solution for this Problem? How can i delete the existing image?
It seems like this could be a weird race condition where the file.exists hasn't released the resource and it is trying to delete prior to release. I would probably try something along these lines.
try
{
File.Delete(file);
}
catch
{
//File does not exist or another error occurred.
}
I found it on my Own.
In PageLoad i use thet "file" also. I forgot to dispose the Image:
foreach (PanelView panel in pv)
{
path = Request.PhysicalPath.Substring(0, Request.PhysicalPath.LastIndexOf('\\') + 1) + subPath + "\\" + GetRaumImageName(panel.Title);
bitMap = new Bitmap(path + ".bmp");
b0 = BmpToMonochromConverter.CopyToBpp(bitMap, 1);
// bounce.updateInterface.UpdateProductImage(b0, panel.Panel.PRODUCT_ID, "", ref update_Handle);
bitMap.Dispose();
}
Anyway thanks for help!
Why delete file in the first place? Can't you make it overwrite the existing file if it already exists?
Another thing you can do is to pause the thread for like 400ms until OS does it's thing and files are completely deleted and all streams closed.

The action can't be completed because the file is open in IIS Worker Process

I am uploading a image for a user & saving it on a specified location. The code is working fine in normal scenario i.e. user selects a image & save it, it works.
Challenge occurs when user selects a image( probably wrong image due to mistake) & don't save it, but again selects a new image & then saves it.
This scenario gives me the error :
"The process cannot access the file because it is being used by another process."
When I try to delete image from the location at the time of error, file can't be deleted with message:
"The action can't be completed because the file is open in IIS Worker Process
Close the file and try again."
Code is like this:
try
{
if (!Directory.Exists(folder))
Directory.CreateDirectory(folder);
msf = new MemoryStream();
bytes=FileUpload1.FileBytes;
msf.Write(bytes, 0, bytes.Length);
using (FileStream stream = new FileStream(folder + "/" + filename, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
{
//converting any graphic file type to jpeg format
Image img = Image.FromStream(msf);
img.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
msf.WriteTo(stream);
IsuploadSuccess = true;
img.Dispose();
}
}
catch
{
IsuploadSuccess = false;
}
finally
{
if (msf != null)
{
msf.Close();
msf.Dispose();
}
}
I have tried adding "FileAccess.ReadWrite" & "FileShare.ReadWrite" in file stream, but doesn't work either with all options in File stream.
Please help...
Instead of getting solution of problem, I finally change approach to get rid to source of challenge. I change file name with UserID (unique) appended with CurrentDateTime converted to string & store it to temp folder until user save the change. This forms a different file each time for the challenge scenario. After save each file in temp folder created by the user (preceded by unique userid) is deleted & last changes are saved to respective directory.
I had this problem and took me few hours to figure it out.
I my case the Bitmap new(path) had locked the file. I had to dispose of it before exiting the using block.
However it is the method by which I debugged it is important.
My approach in pinpointing the source of the problem was to open the folder where the image was saved and tracing the code line by line. After each line I deleted the file and did Ctrl+Z to put it back. If it gave an error when I tried to delete it, then that is the line that locked it. So I got to that line within 5 min.
using (MemoryStream memoryStream = new())
{
if (System.IO.File.Exists(path))
{
using(Bitmap bitmap = new(path)) <-- this solved it
{
ImageConverter imageConverter = new();
bitmap.Save(memoryStream, ImageFormat.Bmp);
bytes = memoryStream.ToArray();
}
}
}

Manipulating freshly uploaded file causes IOException

My Asp.net MVC app requires a file upload. In the course of the upload I'd like to manipulate the freshly uploaded file.
public ActionResult Edit(int id, FormCollection collection) {
Block block = userrep.GetBlock(id);
foreach (string tag in Request.Files) {
var file = Request.Files[tag] as HttpPostedFileBase;
if (file.ContentLength == 0)
continue;
string tempfile = Path.GetTempFileName()
file.SaveAs(tempfile);
// This doesn't seem to make any difference!!
// file.InputStream.Close();
if (FileIsSmallEnough(file)) {
// Will throw an exception!!
File.Move(tempfile, permanentfile);
} else {
GenerateResizedFile(tempfile, permanentfile);
// Will throw an exception!!
File.Delete(tempfile);
}
block.Image = permanentfile;
}
userrep.Save();
The problem with this snippet is that any attempt to manipulate the initially uploaded file generates an IOException("The process cannot access the file because it is being used by another process.") Of course I can bypass the problem by copying rather than moving uploaded file but I still can't delete it once I have a better alternative.
Any advice?
Duffy
As you have mentioned in your comments, you load an Image from file. The MSDN documentation states that the file remains locked until the image is disposed.
http://msdn.microsoft.com/en-us/library/stf701f5.aspx
To dispose your image, you can either call the Dispose method on the instance, or use the preferred mechanism of the using statement:
private bool FileIsSmallEnough()
{
using (Image i = Image.FromFile())
{
}
}
This should solve the problem.

C# Why is my code throwing a io.system.directorynotfound?

Why would the code below throw a io.system.directorynotfound exception? I can't recreate the problem myself but another user of my code does see it, any ideas why?
Thanks
try
{
//create path
string strAppData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData).ToString() + "\\MyApp\\Data\\logs";
//check path exists
if (!System.IO.File.Exists(strAppData))
{
System.IO.Directory.CreateDirectory(strAppData);
}
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(strAppData);
int count = dir.GetFiles().Length;
if (count > 100)
{
string[] files = System.IO.Directory.GetFiles(strAppData);
foreach (string file in files)
{
System.IO.File.Delete(file);
}
}
this.fileName = fileName;
// delete the file if it exists
if (File.Exists(fileName))
{
//delete the file
File.Delete(fileName);
}
// write the data to the file
fs = File.OpenWrite(fileName);
sWriter = new StreamWriter(fs);
sWriter.WriteLine(headerText);
sWriter.Flush();
sWriter.Close();
}
catch (Exception exp)
{
throw new Exception(exp.Message);
}
Have you tried using System.IO.Directory.Exists rather than System.IO.File.Exists when checking to see if the path exists?
You're checking for the existence of a directory using System.IO.File rather than System.IO.Directory. It probably works on your machine because that directory already exists, and so the check doesn't matter.
Either way, you need to remember that the file system is volatile. Rather than checking existence, try to open the resource and handle the exception when it fails.
Check that the directory exists, not the file...
Although you're checking it, and creating it if it doesn't exist. You don't know if they have privelages to create the directory. So your Directory.CreateDirectory call may well be failing too and then sub-sequently the rest of the code will fail
http://msdn.microsoft.com/en-us/library/system.io.file.exists.aspx
"Remarks
The Exists method should not be used for path validation, this method merely checks if the file specified in path exists. Passing an invalid path to Existsl returns false. "
That is your error right there. Your validation does not ensure that the path to the file exists

Categories