Try Catch Statement just not catching exception - c#

I have a simple thumbnail function that I wrote for a program that displays pictures and videos in a folder. If it is a video I want to generate a picture to display. Now it is buggy to do this in folders with tons of files so I put it in a try catch statement and just said first try to get the thumbnail, if that doesn't work get the icon, and if that doesn't work just don't display it. Works fine when I debug but when I hammer it with files in production it occasionally crashes. Not surprising since it runs much faster in production. But clearly, since I only have this shellfile function in only one place, the try catch is not catching the exception.
public class Picture : INotifyPropertyChanged
{
private string _path;
private string _thumbpath;
public string ext { get; set; }
public string Thumbpath
{
get
{
if (_thumbpath != "MOVIE!")
{
return _thumbpath;
}
else
{
try
{
Microsoft.WindowsAPICodePack.Shell.ShellFile shellFile = Microsoft.WindowsAPICodePack.Shell.ShellFile.FromFilePath(_path);
System.Drawing.Bitmap bm = shellFile.Thumbnail.Bitmap;
string filename = "RECTHUMB" + RandomString(7) + ".jpg";
bm.Save(temppath + filename, System.Drawing.Imaging.ImageFormat.Jpeg);
bm.Dispose();
return temppath + filename;
}
catch
{
try
{
System.Drawing.Icon icon = System.Drawing.Icon.ExtractAssociatedIcon(_path);
System.Drawing.Bitmap bm = icon.ToBitmap();
string filename = "RECTHUMB" + RandomString(7) + ".jpg";
bm.Save(temppath + filename, System.Drawing.Imaging.ImageFormat.Jpeg);
//bm.Dispose();
return temppath + filename;
}
catch
{
return "";
}
}
}
}
set
{
_thumbpath = value;
}
}
}
Here is the event log:
<EventData><Data>Application: Meta_Data_Mapper.exe CoreCLR Version:
7.0.222.60605 .NET Version: 7.0.2 Description: The process was terminated due to an unhandled exception. Stack: at
Microsoft.WindowsAPICodePack.Shell.IShellItemImageFactory.GetImage(Size,
SIIGBF, IntPtr ByRef) at
Microsoft.WindowsAPICodePack.Shell.ShellThumbnail.GetHBitmap(System.Windows.Size)
at Meta_Data_Mapper.MainWindow+Picture.get_Thumbpath() at ...

Related

How to extract the .img files using c# [duplicate]

I'm trying to extract an ISO to a folder with the same name without .iso on the end.
I'm having a problem with winrar as it will not start the extract when I start up with the seach starting in the folder with the ISO.
UPDATED with answer code
private void ExtractISO(string toExtract, string folderName)
{
// reads the ISO
CDReader Reader = new CDReader(File.Open(toExtract, FileMode.Open), true);
// passes the root directory the folder name and the folder to extract
ExtractDirectory(Reader.Root, folderName /*+ Path.GetFileNameWithoutExtension(toExtract)*/ + "\\", "");
// clears reader and frees memory
Reader.Dispose();
}
private void ExtractDirectory(DiscDirectoryInfo Dinfo, string RootPath, string PathinISO)
{
if (!string.IsNullOrWhiteSpace(PathinISO))
{
PathinISO += "\\" + Dinfo.Name;
}
RootPath += "\\" + Dinfo.Name;
AppendDirectory(RootPath);
foreach (DiscDirectoryInfo dinfo in Dinfo.GetDirectories())
{
ExtractDirectory(dinfo, RootPath, PathinISO);
}
foreach (DiscFileInfo finfo in Dinfo.GetFiles())
{
using (Stream FileStr = finfo.OpenRead())
{
using (FileStream Fs = File.Create(RootPath + "\\" + finfo.Name)) // Here you can Set the BufferSize Also e.g. File.Create(RootPath + "\\" + finfo.Name, 4 * 1024)
{
FileStr.CopyTo(Fs, 4 * 1024); // Buffer Size is 4 * 1024 but you can modify it in your code as per your need
}
}
}
}
static void AppendDirectory(string path)
{
try
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
}
catch (DirectoryNotFoundException Ex)
{
AppendDirectory(Path.GetDirectoryName(path));
}
catch (PathTooLongException Ex)
{
AppendDirectory(Path.GetDirectoryName(path));
}
}
The user selects the folder to extract (.ISO) toExtract. I then use it in the Process.Start() in the background worker. That just seems to open the mounting software and doesn't extract the ISO to the desired folder name.
Thanks in advance for your help.
Or if anyone could give me a batch to extract the ISO instead and to call it from c# passing toExtract and the folder name that would be helpful too.
Thanks
If external Class Libraries are OK!
Then use SevenZipSharp or .NET DiscUtils to extract ISO's...
These two ClassLibraries can manage ISO and Extract them!
For DiscUtils you can find some codes for ISO Management [CDReader Class] at the Link I provided.
But For SevenZipSharp, Please Explore the ClassLibrary source and find the Code to Extract or Google to find it!
To get the Name of the folder just use Path.GetFileNameWithoutExtension((string)ISOFileName) which will return "ISOFile" for an iso named "ISOFile.iso". And then you can use it with your desired path.
UPDATE
Code To Extract ISO Image with DiscUtils :
using DiscUtils;
using DiscUtils.Iso9660;
void ExtractISO(string ISOName, string ExtractionPath)
{
using (FileStream ISOStream = File.Open(ISOName, FileMode.Open))
{
CDReader Reader = new CDReader(ISOStream, true, true);
ExtractDirectory(Reader.Root, ExtractionPath + Path.GetFileNameWithoutExtension(ISOName) + "\\", "");
Reader.Dispose();
}
}
void ExtractDirectory(DiscDirectoryInfo Dinfo, string RootPath, string PathinISO)
{
if (!string.IsNullOrWhiteSpace(PathinISO))
{
PathinISO += "\\" + Dinfo.Name;
}
RootPath += "\\" + Dinfo.Name;
AppendDirectory(RootPath);
foreach (DiscDirectoryInfo dinfo in Dinfo.GetDirectories())
{
ExtractDirectory(dinfo, RootPath, PathinISO);
}
foreach (DiscFileInfo finfo in Dinfo.GetFiles())
{
using (Stream FileStr = finfo.OpenRead())
{
using (FileStream Fs = File.Create(RootPath + "\\" + finfo.Name)) // Here you can Set the BufferSize Also e.g. File.Create(RootPath + "\\" + finfo.Name, 4 * 1024)
{
FileStr.CopyTo(Fs, 4 * 1024); // Buffer Size is 4 * 1024 but you can modify it in your code as per your need
}
}
}
}
static void AppendDirectory(string path)
{
try
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
}
catch (DirectoryNotFoundException Ex)
{
AppendDirectory(Path.GetDirectoryName(path));
}
catch (PathTooLongException Exx)
{
AppendDirectory(Path.GetDirectoryName(path));
}
}
Use It with Like This :
ExtractISO(ISOFileName, Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "\\");
Working! Tested By Me!
And Of Course You can always add more Optimization to the code...
This Code is Just a Basic One!
For UDF or for making Windows ISO Files after servicing(DISM) with out needs the above accepted answer is not working for me so i tried this working method with DiscUtils
using DiscUtils;
public static void ReadIsoFile(string sIsoFile, string sDestinationRootPath)
{
Stream streamIsoFile = null;
try
{
streamIsoFile = new FileStream(sIsoFile, FileMode.Open);
DiscUtils.FileSystemInfo[] fsia = FileSystemManager.DetectDefaultFileSystems(streamIsoFile);
if (fsia.Length < 1)
{
MessageBox.Show("No valid disc file system detected.");
}
else
{
DiscFileSystem dfs = fsia[0].Open(streamIsoFile);
ReadIsoFolder(dfs, #"", sDestinationRootPath);
return;
}
}
finally
{
if (streamIsoFile != null)
{
streamIsoFile.Close();
}
}
}
public static void ReadIsoFolder(DiscFileSystem cdReader, string sIsoPath, string sDestinationRootPath)
{
try
{
string[] saFiles = cdReader.GetFiles(sIsoPath);
foreach (string sFile in saFiles)
{
DiscFileInfo dfiIso = cdReader.GetFileInfo(sFile);
string sDestinationPath = Path.Combine(sDestinationRootPath, dfiIso.DirectoryName.Substring(0, dfiIso.DirectoryName.Length - 1));
if (!Directory.Exists(sDestinationPath))
{
Directory.CreateDirectory(sDestinationPath);
}
string sDestinationFile = Path.Combine(sDestinationPath, dfiIso.Name);
SparseStream streamIsoFile = cdReader.OpenFile(sFile, FileMode.Open);
FileStream fsDest = new FileStream(sDestinationFile, FileMode.Create);
byte[] baData = new byte[0x4000];
while (true)
{
int nReadCount = streamIsoFile.Read(baData, 0, baData.Length);
if (nReadCount < 1)
{
break;
}
else
{
fsDest.Write(baData, 0, nReadCount);
}
}
streamIsoFile.Close();
fsDest.Close();
}
string[] saDirectories = cdReader.GetDirectories(sIsoPath);
foreach (string sDirectory in saDirectories)
{
ReadIsoFolder(cdReader, sDirectory, sDestinationRootPath);
}
return;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
it has extracted from a application source ISOReader but modified for my requirements
total source is available at http://www.java2s.com/Open-Source/CSharp_Free_CodeDownload/i/isoreader.zip
Try this:
string Desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
Process.Start("Winrar.exe", string.Format("x {0} {1}",
Desktop + "\\test.rar",
Desktop + "\\SomeFolder"));
That would extract the file test.rar to the folder SomeFolder. You can change the .rar extention to .iso, it'll work the same.
As far as I can see in your current code, there is no command given to extract a file, and no path to the file that has to be extracted. Try this example and let me know if it works =]
P.S. If you'd like to hide the extracting screen, you can set the YourProcessInfo.WindowStyle to ProcessWindowStyle.Hidden.
I hace confrunted recently with this kind of .iso extraction issue. After trying several methods, 7zip did the job for me, you just have to make sure that the latest version of 7zip is installed on your system. Maybe it will help
try
{
Process cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.CreateNoWindow = false;
cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
cmd.Start();
cmd.StandardInput.WriteLine("C:");
//Console.WriteLine(cmd.StandardOutput.Read());
cmd.StandardInput.Flush();
cmd.StandardInput.WriteLine("cd C:\\\"Program Files\"\\7-Zip\\");
//Console.WriteLine(cmd.StandardOutput.ReadToEnd());
cmd.StandardInput.Flush();
cmd.StandardInput.WriteLine(string.Format("7z x -y -o{0} {1}", source, copyISOLocation.TempIsoPath));
//Console.WriteLine(cmd.StandardOutput.ReadToEnd());
cmd.StandardInput.Flush();
cmd.StandardInput.Close();
cmd.WaitForExit();
Console.WriteLine(cmd.StandardOutput.ReadToEnd());
}
catch (Exception e)
{
Console.WriteLine(e.Message + "\n" + e.StackTrace);
if (e.InnerException != null)
{
Console.WriteLine(e.InnerException.Message + "\n" + e.InnerException.StackTrace);
}
}

Throw exception in test method using MSTest

I'm using MSTest to write test cases for my application.
I have a method where files are moved from one directory to another directory. Now when I run code coverage, it shows that the catch block is not covered in code coverage.
This is my code as below.
class Class1
{
public virtual bool MoveFiles( string fileName)
{
bool retVal = false;
try
{
string sourcePath = "PathSource";
string destinationPath = "DestPath";
if (Directory.Exists(sourcePath) && Directory.Exists(destinationPath))
{
string finalPath = sourcePath + "\\" + fileName ;
if (Directory.Exists(finalPath))
{
File.Move(finalPath, destinationPath);
retVal = true;
}
}
}
catch (Exception ex)
{
LogMessage("Exception Details: " + ex.Message);
retVal = false;
}
return retVal;
}
}
The test method for the above code is this.
[TestMethod()]
public void MoveFilesTest()
{
string filename = "test";
Class1 serviceObj = new Class1();
var result = serviceObj.MoveFiles(filename);
Assert.IsTrue(result);
}
When I run my code coverage, it shows only the try block is covered and not the catch block. So in order to do that, I need to write another test method and generate an exception and test method will look something like this.
[TestMethod()]
public void MoveFilesTest_Exception()
{
string filename = "test";
Class1 serviceObj = new Class1();
ExceptionAssert.Throws<Exception>(() => serviceObj.MoveFiles(filename));
}
Can anyone help to create an exception for this code as I couldn't do that or at least guide me how to do it?
Many thanks!
You can use the Expected Exception Attribute in your tests to indicate that an exception is expected during execution.
The following code will test for invalid characters in the filename and should raise an ArgumentException since > is an invalid character in filenames:
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void InvalidCharacterInFileNameTest()
{
string filename = "test>";
Class1 serviceObj = new Class1();
serviceObj.MoveFiles(filename);
}
Update:
Since the Directory.Exists() 'supresses' any exception that might occur, you also need to change the code in your function to throw an exception if the source file does not exist or is invalid.
This is just an example to show how it can be implemented but your code could look similar to this:
public virtual bool MoveFiles(string fileName)
{
bool retVal = false;
try
{
string sourcePath = "PathSource";
string destinationPath = "DestPath";
if (Directory.Exists(sourcePath) && Directory.Exists(destinationPath))
{
string finalPath = sourcePath + "\\" + fileName;
if (Directory.Exists(finalPath))
{
File.Move(finalPath, destinationPath);
retVal = true;
}
else
{
throw new ArgumentException("Source file does not exists");
}
}
}
catch (Exception ex)
{
LogMessage("Exception Details: " + ex.Message);
retVal = false;
}
return retVal;
}

ExternalException: A generic error occurred in GDI+

I am using Selenium WebDriver in C# and
I am trying to dynamically create a folder and save screenshots of failing tests to it.
Here I am running the group of test cases (Test Suite of 66 test cases).
After running the test suite I found few failed tests with GDI+ error and were not captured as a screenshot.
But when I run them individually most of the failed cases (GDI+ error) were passing except few.
Here is the code for creating a folder:
TestExecutionStartTime = DateTime.Now;
baseDirectory = AppDomain.CurrentDomain.BaseDirectory + #"\" + ConfigurationManager.AppSettings.GetValues("failedTests")[0];
Browser = ConfigurationManager.AppSettings["WebDriver"];
DirectoryInfo directory = new DirectoryInfo(baseDirectory);
DirectoryInfo[] subdirs = directory.GetDirectories();
if (System.IO.Directory.GetDirectories(baseDirectory).Length == 0)
{
screenshotDirectory = baseDirectory + #"\" + (DateTime.Now.ToString("yyyy_MM_dd_hh_mm") + "_" + Browser);
Directory.CreateDirectory(screenshotDirectory);
}
Here is the code for taking screenshot:
public void takeScreenshot(string filename)
{
string fname = filename + ".jpg";
string screenshot = screenshotDirectory + #"\" + fname;
Screenshot ss = ((ITakesScreenshot)WebDriver).GetScreenshot();
byte[] image = ss.AsByteArray;
using (MemoryStream ms = new MemoryStream(image))
{
Image i = Image.FromStream(ms);
i.Save(screenshot);
}
I assume that the error is at this i.Save(screenshot) call, but I was not able to resolve it.
I have reason to believe (from experience) that your issue comes about as a result of the stream being destroyed while it is being saved (the using statement).
Things to be aware of:
Write permissions wherever you are saving the image
Make sure the path is correct - this will throw a GDI+ exception and is very misleading, verify your path, try a temporary directory instead of creating your custom image directory to rule this one out.
Make sure the height of the image is not bigger than (65534px)
You can verify this by looking at the size:
var bitmapTemp = new Bitmap(stream);
Console.WriteLine(bitmapTemp.Height);
Here's some code that destroys the stream only after the image is saved:
public static Screenshot GetScreenshot(ChromeDriver driver)
{
Screenshot ss = ((ITakesScreenshot)driver).GetScreenshot();
return ss;
}
public static void SaveScreenshot(byte[] byteArray, string location)
{
var stream = new MemoryStream(byteArray);
var img = Image.FromStream(stream);
img.Save(location);
stream.Dispose();
}
And use the functions like so:
var path = AppDomain.CurrentDomain.BaseDirectory;
var ss = GetScreenshot(driver);
SaveScreenshot(ss.AsByteArray, path + "imagename.jpg");
Thanks for your inputs AntonB.
I have considered your points and tried differently and got the solution.
i have used [SetUpFixture], [OneTimeSetUp] and [OneTimeTearDown] to create folder only once and it solved the problem.
Here is the code:
[SetUpFixture]
public class Config
{
public Config()
{
}
public string baseDirectory;
public static string screenshotDirectory;
[OneTimeSetUp]
public void SetUp()
{
Console.WriteLine("Creating a folder to capture failed scenarios");
baseDirectory = AppDomain.CurrentDomain.BaseDirectory + #"\" + ConfigurationManager.AppSettings.GetValues("failedTests")[0];
string Browser = ConfigurationManager.AppSettings["WebDriver"];
screenshotDirectory = baseDirectory + #"\" + (DateTime.Now.ToString("yyyy_MM_dd_hh_mm") + "_" + Browser);
Directory.CreateDirectory(screenshotDirectory);
}
[OneTimeTearDown]
public void TearDown()
{
}
}

Loading an image as Texture2D

In my program, I want to save some screenshots and load them later on to compute somethings. I created a methode to compute the image names:
static public string generatePhotoName (string cameraName, float time)
{
return "G:/Data/unity/cameraDemo/" +
DataController.measurmentPath +
"/photos" + "/" +
cameraName + "/" +
time.ToString () + "_" + cameraName + ".png";
}
This worked fine for saving, but when I try to load an image, File.Exists (filePath)returns false.
But when I hardcoded the filepath, loading works fine too:
static public string generatePhotoName (string cameraName, float time)
{
return "G:/Data/unity/cameraDemo/demo/photos/Camera/test.png";
}
It even works with "real" image names(i.e. 3.827817_Camera.png).
Using Path.Combine(...) and changing "/" to "\" did not change anything...
// edit: this is my load methode
static public Texture2D loadPhotoToTexture (string filePath)
{
Texture2D tex = null;
byte[] fileData;
if (File.Exists (filePath)) {
fileData = File.ReadAllBytes (filePath);
tex = new Texture2D (2, 2);
tex.LoadImage (fileData); //..this will auto-resize the texture dimensions.
} else {
Debug.Log (filePath + " does not exist");
}
return tex;
}`
// edit2: some more code
This is how I call the methode
Texture2D photo = DataController.loadPhotoToTexture(photoData.getFileName ());
And this is my class PhotoData
public class PhotoData : BaseData
{
private string _cameraName;
public string cameraName {
get { return _cameraName; }
set { _cameraName = value; }
}
private float _time;
public float time {
get { return _time; }
set { _time = value; }
}
public PhotoData ()
{
}
public PhotoData (string cameraName, float time)
{
_cameraName = cameraName;
_time = time;
}
public string getFileName ()
{
return PlayerController.generatePhotoName (_cameraName, _time);
}
}
The problem was, that I tried to save and load the screenshots in one Update()-call.
I fixed it by changing it to right-click to take and save a screenshot and left-click to load the screenshot.
If you want to store images to a certain file on disk, not inside your game folder structure, do this: create a folder, and store its location (filepath). For example:
string screenshotFileName = time.ToString () + "_" + cameraName + ".png"
string screenshotDirectory;
screenshotDirectory = #"C:\someFolder\anotherFolder\";
try { Directory.CreateDirectory(directory); }
catch (Exception e)
{ //you should catch each exception separately
if (e is DirectoryNotFoundException || e is UnauthorizedAccessException)
Debug.LogError("OMG PANIC");
}
FileInfo filepath = new FileInfo(screenshotDirectory+screenshotFileName);
if(filepath.Exists)
{
//load the file
}
You could also simply create a folder, with a relative path, which will be in the same folder as your executable, by changing the screenshotDirectory to
screenshotDirectory = #"screenshots\"+cameraName+#"\";
Edit:
You seem to load the texture correctly. Are you assigning it to the material's main texture? Where is your code encountering the problem? For example if you're running this script on the same object that you want the texture to be applied:
this.GetComponent<Renderer>().material.mainTexture = loadedTexture;
Also, when you want to load images, it's best that you use the Resources folder, which uses forwards slashes, not . Store everything that you might want to load on runtime there, and use Resources.Load().

OutOfMemoryException error in Loop

I am trying to create a Windows app which uploads files to FTP. Essentially, it looks for .jpeg files in a given folder, it reads through the barcodes found in the .jpg files before uploading it into the FTP server, and entering the URL into the database for our records.
As there will be multiple files at any given time in the folder, I am essentially trying to read them in a loop, and process them accordingly. However, I get an OutOfMemoryException whenever the loop starts again. I am trying to figure out what I'm doing wrong here. I have appended my code below:
private void btnProcess_Click(object sender, RoutedEventArgs e)
{
podPath = Directory.GetFiles(DestPath, "*.jpg");
List<string> scans = new List<string>(podPath.Length);
List<string> badscans = new List<string>();
byte[] imageBytes;
string filename, result;
POD conpod = new POD();
OTPOD otpod = new OTPOD();
ConsignmentObj scanJob;
//Pickup OTScan;
//Consolidate ccv;
for (int i = 0; i < podPath.Count(); i++ )
{
filename = podPath[i].ToString();
using (Bitmap bm = (Bitmap)Bitmap.FromFile(filename))
{
var results = barcodeReader.Decode(bm);
result = results.ToString();
bm.Dispose();
}
if (result != null)
{
//if barcode can be read, we throw the value into the database to pull out relevant information
if (result.Contains(ConNotePrefix))
{
#region Consignments
scanJob = getCon(result.ToString());
final = ImageFolder + "\\" + result.ToString() + ".jpg";
using (System.Drawing.Image img = System.Drawing.Image.FromFile(filename))
{
MemoryStream ms = new MemoryStream();
try
{
img.Save(ms, ImageFormat.Jpeg);
imageBytes = ms.ToArray();
img.Dispose();
}
finally
{
ms.Flush();
ms.Close();
ms.Dispose();
}
}
lock (filename)
{
if (System.IO.File.Exists(filename))
{
File.Delete(filename);
}
}
using (var stream = File.Create(final)) { }
File.WriteAllBytes(final, imageBytes);
File.Delete(filename);
conpod.ConsignmentID = scanJob.ConsignmentID;
conpod.UserID = 1;
conpod.Location = ftpUrl + "//" + result.ToString() + ".jpg";
conpod.rowguid = Guid.NewGuid();
UploadFilesToFtp(ftpUrl, ftpUser, ftpPass, final, result.ToString() + ".jpg");
insertPOD(conpod);
scans.Add(result.ToString());
#endregion
}
}
else
{
badscans.Add(filename);
}
}
this.lbScans.ItemsSource = scans;
this.lbBadScans.ItemsSource = badscans;
}
The FTP method, UploadFilesToFtp(x, x, x, x, x, x) is not a problem here. All feedback will be much appreciated.
An OutOfMemoryException can also be thrown by the method FromFile of the Image class when
The file does not have a valid image format.
or
GDI+ does not support the pixel format of the file.
So i think there is a problem with one of your image files you are reading. One solution is to catch the OutOfMemoryException and adding the file to the badscans.
try{
using (Bitmap bm = (Bitmap)Bitmap.FromFile(filename)) {
var results = barcodeReader.Decode(bm);
result = results.ToString();
bm.Dispose();
}
}
catch(OutOfMemoryException) {
badscans.add(filename);
}

Categories

Resources