In Asp.net i'm not able to catch any exception properly? - c#

In Asp.net (c#),i'm not able to catch exception(FileNotFoundException) properly... i don't know the reason..Actually File s not there..But catch statement fails to catch the exception..
here is the code..
try
{
System.Drawing.Image imgg1 = System.Drawing.Image.FromFile(Server.MapPath("").ToString() + "\\images\\img1.jpg");
}
catch (FileNotFoundException)
{
Response.Write("<script>alert('Please Select and upload Student's Photo');</script>");
}

you can find out what type is being thrown
try
{
System.Drawing.Image imgg1 = System.Drawing.Image.FromFile(Server.MapPath("").ToString() + "\\images\\img1.jpg");
}
catch (FileNotFoundException)
{
Response.Write("<script>alert('Please Select and upload Student's Photo');</script>");
}
catch(Exception ex)
{
Response.Write("Ex: " + ex.GetType().ToString());
}

Are you sure that's the exception your getting?
You should try to replace the FileNotFoundException to just Exception and check what exception is being trown.
EDIT:
Q1: In the debug mode, is the code actually entering the catch session?
Could you rebuild (Ctrl+Shift+B in Visual Studio) that code?
Your actually writing a code that will fail
there's an ending quote in here:
alert('Please Select and upload Student's Photo');
See in the sintax highlighter
replace for this
alert('Please Select and upload Student\'s Photo');

Your javascript quoted text is not balanced
try
alert('please upload student\'s photo');

Check if it exists rather than catch that exception.
string path = Server.MapPath("~/images/img1.jpg");
if (System.IO.File.Exists(path))
{
System.Drawing.Image imgg1 = System.Drawing.Image.FromFile(path);
}
else
{
Page.ClientScript.RegisterStartupScript(Page.GetType(), "notfound", "alert(\"Please Select and upload Student's Photo\");", true);
}
You are also escaping your javascript message too early
'Please Select and upload Student's Photo'

The exception thrown is not of type FileNotFoundException, try catching Exception instead and see if it works

Try stepping through your code in the debugger and see if the exception is truly not being caught. It may also help to include a specific variable to hold your FileNotFoundException, and to include a fallback catch of a general exception, like so:
try
{
System.Drawing.Image imgg1 = System.Drawing.Image.FromFile(Server.MapPath("").ToString() + "\\images\\img1.jpg");
}
catch (FileNotFoundException fnfe)
{
Response.Write("<script>alert('Please Select and upload Student's Photo');</script>");
}
catch (Exception ex)
{
// do something with the exception
}

If (in the original example) you are trying to write a javascript alert out to the page you have to surround your alert() it with <script></script> tags.
BUT why are you using try-catch blocks like that when you could use System.IO.File.Exists(path), and an error label ?
using System.IO;
using System.Drawing;
...
String filePath = Server.MapPath("").ToString() + "\images\img1.jpg";
if(File.Exists(filePath))
{
Image imgg1 = Image.FromFile(filePath);
}
else
{
lblError.Text = "Please upload a picture for this student";
lblError.Visible = true;
}

The problem is not related to the catch block. It's the way your using C# to create the JavaScript. Response.Write will pile the output prior to the rendering of the page. So it wont be recognized by the browser. Do this instead.
catch (FileNotFoundException)
{
String csname1 = "Popup";
if (!IsClientScriptBlockRegistered(csname1))
{
String cstext1 = "<script type=\"text/javascript\">" + "alert('Please Select and upload Student\\'s Photo');</" + "script>";
RegisterStartupScript(csname1, cstext1);
}
}
If you still don't believe me just do this to prove it to yourself.
catch(FileNotFoundException)
{
Response.Write("its working")
}
And don't just look at the rendered page which is going to be browser dependant, right click and view source so you can see what's really going on.

Your exception is being thrown, but you aren't seeing your alert because you're not writing out JavaScript. Try this:
try
{
System.Drawing.Image imgg1 = System.Drawing.Image.FromFile(Server.MapPath("").ToString() + #"\images\img1.jpg");
}
catch (FileNotFoundException)
{
Page.RegisterClientScriptBlock("myScript", "<script language=javascript>alert('Please Select and upload Student's Photo');</script");
}

Related

C# else statement not run when file not found

EDIT:
My problem has been solved thanks to the user Chris Larabell, thank you to all that responded.
The issue that is happening with my code is that when the said file is not present in the Desktop directory, the console will close and will not go to the else statement for what happens when the file is not present. When the file is present however, the console will work completely fine, it is just the else statement.
Here is my code that is being used.
if (inputDrive == "search.system")
{
try
{
string Desktop = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
string DeleteFile = #"delete.txt";
string[] fileList = System.IO.Directory.GetFiles(Desktop, DeleteFile);
foreach (string file in fileList)
{
if (System.IO.File.Exists(file))
{
System.IO.File.Delete(file);
Console.WriteLine("File has been deleted");
Console.ReadLine();
}
else
{
Console.Write("File could not be found");
Console.ReadLine();
}
}
}
catch (System.IO.FileNotFoundException)
{
Console.WriteLine("search has encountered an error");
Console.ReadLine();
}
}
What I am trying to accomplish is to find a file through the Desktop directory with the name of 'delete.txt' and to delete it when the user enters "search.system". the console would then say back to you that the file has been deleted. If the file has not been found, it would say that "the file could not be found" back to you through console. If an error would to occur, it would go to catch and say "search has encountered an error"
I also want to say that I am sorry if this code is messy and/or if this is completely wrong from what I am trying to accomplish. I am new to C#, and new to coding in general.
You would want to put an if statement to check that the fileList length is > 0. If the file length is zero, the file was not found. Otherwise, you can proceed to delete the file.
Also, don’t be discouraged as a new coder. Set a breakpoint at the line where you use the GetFiles() method and step (F11) to the next line. Hover your cursor over the fileList variable and see if the number of items in the array is zero.
System.IO.Directory.GetFiles()
It looks like you are simply looking for a specific file by name and deleting it if it exists. You could simplify your code by doing this:
if (inputDrive == "search.system")
{
try
{
string Desktop = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
string DeleteFile = #"delete.txt";
string filePath = System.IO.Path.Combine(Desktop, DeleteFile);
if (System.IO.File.Exists(filePath))
{
System.IO.File.Delete(filePath);
Console.WriteLine("File has been deleted");
Console.ReadLine();
}
else
{
Console.Write("File could not be found");
Console.ReadLine();
}
}
catch (System.Exception ex)
{
Console.WriteLine($"search has encountered an error: {ex}");
Console.ReadLine();
}
}

Catch System.ArgumentException The URL cannot be empty

I'm trying to the catch System.ArgumentException "The URL cannot be empty." and display a message:
catch (System.ArgumentException errormsg)
{
string errorVar = Convert.ToString(errormsg);
if (errorVar == "System.ArgumentException: The URL cannot be empty.")
{
MessageBox.Show("The URL / Filename cannot be empty. Please check and try again");
}
else
{
MessageBox.Show("There is no message for this error:- " + errorVar);
}
}
At the moment, it keeps running the "Else" scenario with the message box of :
NB: line 153 = doc.Load(openFileDialog1.FileName);
Could someone please help me get it running the "if" instead of the "else" ?
Instead of trying to parse the exception, you should be looking at what causes it. In this case, the problem is that openFileDialog1.FileName is empty, so, what you should be doing is something like this:
try
{
if (string.IsNullOrEmpty(openFileDialog1.FileName))
{
MessageBox.Show("You need to select the file to open");
}
else
{
// Only attempt to do this if you know the user selected some value
doc.Load(openFileDialog1.FileName);
}
}
catch (ArgumentException ex)
{
//Show some error that is not caused by the URL being empty
}
As a general rule, you need to validate user input before attempting to use it.
string errorVar = errormsg.Message; //this would give you the error message
then you can compare it
if (errorVar.Equals("The URL cannot be empty."))
you can also use .Contains or .StartsWith

Trouble Moving files in C#?

I am making a software that will move files from the downloads folder to a specific sub folder in a directory. The sub folder is selected by the user by a combobox. I keep getting this error: System.IO.IOException: Cannot create a file when that file already exists. Also, these error come up on people's computer who install my program...exceptions and things. How do i turn it off. Also, why do i get this error? Here is my code:
string pathUser4 = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
string pathDownload4 = (pathUser4 + #"\Downloads\");
string sourceFile = pathDownload4 + listBox1.Text;
string pathdoc5 = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string pathDownload5 = (pathdoc5 + #"\iracing\setups\");
string destinationFile = pathDownload5 + comboBox1.Text;
File.Move(sourceFile, destinationFile);
if (comboBox1.Text == "Select File Destination")
{
MessageBox.Show("Please Select A Destination Folder", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
Each File.Move should be wrapped in a try/catch block as you can never expect an IO operation to execute without error. It could be something as simple as the user having a file handle open, or the file existing in the destination folder, either way, you don't want a single file to throw an exception that stops the entire operation. You will want to catch the exceptions and log them either to an error log file or to the event log, this way you can see the errors that occurred but it will not interrupt anything.
Secondly, for any desktop application I would add global error handling to log any uncaught errors. You can do this by putting this code at the beginning of your program,
AppDomain.CurrentDomain.UnhandledException += (a, exception) => File.AppendAllText("errorlog.txt", exception.ToString() + "\n"
This will keep the user from ever seeing ugly exceptions being thrown. Also be sure you are not giving the users the .pdb files as this will cause exceptions to contain paths of the computer it was compiled on which can contain your username and other sensitive information you wouldn't want a client to see.
You can register the global exception handling when the main window is initialized, you want it to be the first thing you do before any thing else because again you never know when an exception will be thrown so you have to think defensively.
public partial class MainWindow : Window
{
public MainWindow()
{
AppDomain.CurrentDomain.UnhandledException += (a, exception) => File.AppendAllText("errorlog.txt", exception.ToString() + "\n");
InitializeComponent();
}
}
C# uses exceptions extensively so it will be good concept for you to study up on if you are not familiar with this type of error handling. All exceptions derive from the Exception class so when you write catch (Exception e) this will catch all exceptions (because a base reference can hold an object of a derived type), however if you know the specific exception a method will throw you can catch a more specific exception (always before the more general catch) and handle it in a specific way. In this example you may have an IOException from the File.Move() that you want to catch and handle differently.
try
{
string pathUser4 = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
string pathDownload4 = (pathUser4 + #"\Downloads\");
string sourceFile = pathDownload4 + listBox1.Text;
string pathdoc5 = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string pathDownload5 = (pathdoc5 + #"\iracing\setups\");
string destinationFile = pathDownload5 + comboBox1.Text;
File.Move(sourceFile, destinationFile);
if (comboBox1.Text == "Select File Destination")
{
MessageBox.Show("Please Select A Destination Folder", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception e)
{
File.AppendAllText("ErrorLog.txt", e.ToString() + "\n");
}
The example code from MSDN for File.Move should get you pointed at the various things you need to deal with, such as an already existing file and basic error handling.
using System;
using System.IO;
class Test
{
public static void Main()
{
string path = #"c:\temp\MyTest.txt";
string path2 = #"c:\temp2\MyTest.txt";
try
{
if (!File.Exists(path))
{
// This statement ensures that the file is created,
// but the handle is not kept.
using (FileStream fs = File.Create(path)) {}
}
// Ensure that the target does not exist.
if (File.Exists(path2))
File.Delete(path2);
// Move the file.
File.Move(path, path2);
Console.WriteLine("{0} was moved to {1}.", path, path2);
// See if the original exists now.
if (File.Exists(path))
{
Console.WriteLine("The original file still exists, which is unexpected.");
}
else
{
Console.WriteLine("The original file no longer exists, which is expected.");
}
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
}
}
The error may caused by your code, or by some invalid input.
As #Despertar mentioned, I suggest all the program include error handling and log features in your code. It will be very helpful for your debug.
But I suggest use open source log library, not do it by yourself. For example, log4net, NLog, etc.

Permission problem with bitmap.Save()

I have this simple code:
System.Drawing.Bitmap bm = bitmapSourceToBitmap(source);
try
{
bm.Save(#"C:\Seva\testeImagem.jpg");
}
catch (Exception ex)
{
}
This throws: Generic Error GDI+.
Anyway, I seached and people say that the problem is with permissions. How can I give permissions to it? Thanks
First find out under what credentials the code is running.
Then check (and, when needed, fix) the security/NTFS settings of the Seva folder.
Especially when this code is running from within a website or service the account will not have permissions to write to the folder.
instead of saving to C:\Seva\testeImagem.jpg why not try saving to
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
"testeImagem.jpg");
You must ensure that the Seva folder exists under C:\ and ensure that the current user has permissions to write to\create this folder. Also, its considered bad practice to write to folders that the user doesn't own. If the user is Running As A Normal User (not an admin) failure to do so results in permission exceptions.
Could you test if the folder exists?
void BitmapCopy(System.Drawing.Bitmap source, string filename) {
if (!String.IsNullOrEmpty(filename) && (source != null)) {
string dirName = #"C:\Seva";
if (!System.IO.Directory.Exists(dirName)) {
dirName = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
}
string bmpFile = System.IO.Path.Combine(dirName, filename);
System.Drawing.Bitmap bm = bitmapSourceToBitmap(source);
try {
bm.Save(bmpFile);
} catch (ArgumentNullException ex) {
Console.WriteLine(ex.Message);
} catch (System.Runtime.InteropServices.ExternalException ex) {
Console.WriteLine(ex.Message);
}
}
}

how to show exception variable value in alert box in asp.net using C#

I have the following code, but the alert box is not displaying.
try
{
do something..
}
catch(Exception ex)
{
Response.Write("<script>alert('"+ex+"')</script>");
}
If I use this code, the alert box appears.
try
{
do some thing
}
catch (Exception ex)
{
Response.Write("<script>alert(\"an error occur\")</script>");
}
How can I display the exception variable in an alert box?
If you want to show the stacktrace:
Response.Write("<script>alert('"+ Server.HtmlEncode(ex.ToString()) + "')</script>");
or if you want only the message
Response.Write("<script>alert('"+ Server.HtmlEncode(ex.Message) + "')</script>");
Try something like
Response.Write("<script>alert('"+ex.Message+"')</script>");
Have a look at the class Exception Class
Dim message = New JavaScriptSerializer().Serialize(rs)
Dim script = String.Format("alert({0});", message)
ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), "", Script, True)
Please check whthr you r using update panel in that page.It may sometimes work if the update panel is there.
You need to be careful and properly escape the Javascript string you are generating ... Imagine there are single quotes in the Exception's message ...
Single-quotes (') need to be escaped (\')
Response.Write("<script>alert('"+ Server.HtmlEncode(ex.Message).Replace("'","\\'" ) + "')</script>");
This solved my problem:
string jscriptCustInfo = "<script type='text/javascript' language='javascript'>";
jscriptCustInfo = jscriptCustInfo + "alert('Dividend Posting Done, Batch No: "+lblBatch.Text+"');";
jscriptCustInfo = jscriptCustInfo + "</script>";
ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", jscriptCustInfo, false);

Categories

Resources