HttpWebResponse hanging up - c#

try
{
responseFile = (HttpWebResponse)requestFile.GetResponse();
}
catch (WebException exRequestFile)
{
MessageBox.Show(exRequestFile.Message);
closeRequest = false;
}
and
if(closeRequest == true) responseFile.Close();
So now my problem:
If i try to download a file, it does so, closes the response. All good.
However, if I type wrong URL (with 404 returned or smth), I can't close the response because it gives me nullreference error. So I close it only when I get a response.
However, after providing wrong URL and not closing response, further tries to download anything result in timeout (even if URL is correct).
Why is that happening and can I resolve it somehow?
EDIT: Full code of class:
public void DownloadAndReplace(string webFile, string sourceFile)
{
var requestFile = (HttpWebRequest)WebRequest.Create(webFile);
var requestMD5 = (HttpWebRequest)WebRequest.Create(webFile + ".md5");
var requestSHA = (HttpWebRequest)WebRequest.Create(webFile + ".sha");
bool closeRequest = true;
_location = sourceFile + "\\" + OriginalFileName(webFile);
requestFile.Method = "HEAD";
requestFile.Timeout = 2000;
HttpWebResponse responseFile = null;
HttpWebResponse responseMD5 = null;
HttpWebResponse responseSHA = null;
try
{
responseFile = (HttpWebResponse)requestFile.GetResponse();
}
catch (WebException exRequestFile)
{
MessageBox.Show(exRequestFile.Message);
closeRequest = false;
}
if (!File.Exists(_location) || responseFile.LastModified > File.GetLastWriteTime(_location))
{
downloadFile(webFile, _location);
if (_controlsRef.chooseMD5.Checked)
{
try
{
responseMD5 = (HttpWebResponse)requestMD5.GetResponse();
downloadFile(webFile + ".md5", _location);
responseMD5.Close();
}
catch (WebException exRequestFile)
{
MessageBox.Show(exRequestFile.Message + " " + webFile + ".md5");
}
}
else if (_controlsRef.chooseSHA1.Checked)
{
try
{
responseSHA = (HttpWebResponse)requestSHA.GetResponse();
downloadFile(webFile + ".sha", _location);
responseSHA.Close();
}
catch (WebException exRequestFile)
{
MessageBox.Show(exRequestFile.Message + " " + webFile + ".sha");
}
}
}
else MessageBox.Show("Newest version");
if(closeRequest == true) responseFile.Close();
public void downloadFile(string urlAddress, string location)
{
_fileHasher = new HashFile(_controlsRef);
using (var downloadClient = new WebClient())
{
downloadClient.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(Completed);
downloadClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
Uri URL = new Uri(urlAddress);
if (location == Environment.GetFolderPath(Environment.SpecialFolder.Desktop))
{
location = location + "\\" + OriginalFileName(urlAddress);
this._location = location;
}
else location = _location;
_downloadStopWatch.Start();
if (File.Exists(location))
{
File.Delete(location);
}
if (_isFile == true)
{
try
{
downloadClient.DownloadFileAsync(URL, location);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
_isFile = false;
}
}
}
}
private string OriginalFileName(string urlAddress)
{
var requestFile = (HttpWebRequest)WebRequest.Create(urlAddress);
requestFile.Method = "HEAD";
HttpWebResponse responseFile = null;
string originalFileName = "";
try
{
responseFile = (HttpWebResponse)requestFile.GetResponse();
}
catch (WebException exResponse)
{
MessageBox.Show(exResponse.Message);
_isFile = false;
}
if (_isFile == true)
{
int segmentLenght = responseFile.ResponseUri.Segments.Length;
originalFileName = responseFile.ResponseUri.Segments[segmentLenght - 1];
responseFile.Close();
}
return originalFileName;
}
To further clarify:
I provide URL for existing file 1. All is ok.
I provide URL for existing file 2. All is ok.
I provide URL for non-exisitng file 3. It throws me an 404 error.
I provide URL for existing file 4. I get program hangup and timeout.

Wrap your HttpWebResponse inside a using statement so that the object can be disposed correctly.
Something like this:
try
{
using(responseFile = (HttpWebResponse)requestFile.GetResponse())
{
...your code...
}
}
catch (WebException exRequestFile)
{
MessageBox.Show(exRequestFile.Message);
closeRequest = false;
}
"using" reference: https://msdn.microsoft.com/en-us/library/yh598w02.aspx

Related

How to know when a method finish in controller

I have a problem with this method, i want to return a PDF file and when the method it's over i want to delete de file from the directory.
public ActionResult DescargaPdfCompara(string id)
{
var rutaPdf = string.Empty;
var type = "application/pdf";
try
{
DateTime ahora = DateTime.Now;
var numeroAleatorio = new Random();
int numeroRandomico = numeroAleatorio.Next(100000000, 1000000000);
string Ruta = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, #"Reportes\" + Convert.ToString(ahora.Year + ahora.Month + ahora.Day + ahora.Hour + ahora.Minute + ahora.Second + numeroRandomico) + ".pdf");
var result = SimuModel.ObtenerSabanaReporteComparativo(id);
var resumen = SimuModel.ObtenerPreExcel(result);
SimuModel.GenerarPdfCompa(result, resumen, Ruta);
rutaPdf = Ruta;
return File(rutaPdf, type);
}
catch (Exception e)
{
throw e;
}
finally
{
System.IO.File.Delete(rutaPdf);
}
}
In the finally i delete the file but i got an error because the method can't find the file, for some reason the method delete the file before return it.
PD: Sorry for my english, i'm from Chile.
Thanks fro your answers!
You can use System.IO.File.ReadAllBytes to read all the file contents to memory, then delete the file and return the contents with another overload of Controller.File method:
public ActionResult GetFile()
{
var fileName = Path.GetTempFileName();
System.IO.File.WriteAllText(fileName, "Hola, Chile!");
var bytes = System.IO.File.ReadAllBytes(fileName);
System.IO.File.Delete(fileName);
return File(bytes, "text/plain", "file.txt");
}
Change return type ContentResult
remove finally section.
public ContentResult DescargaPdfCompara(string id)
{
var rutaPdf = string.Empty;
var type = "application/pdf";
try
{
DateTime ahora = DateTime.Now;
var numeroAleatorio = new Random();
int numeroRandomico = numeroAleatorio.Next(100000000, 1000000000);
string Ruta = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, #"Reportes\" + Convert.ToString(ahora.Year + ahora.Month + ahora.Day + ahora.Hour + ahora.Minute + ahora.Second + numeroRandomico) + ".pdf");
var result = SimuModel.ObtenerSabanaReporteComparativo(id);
var resumen = SimuModel.ObtenerPreExcel(result);
SimuModel.GenerarPdfCompa(result, resumen, Ruta);
rutaPdf = Ruta;
return Content(rutaPdf, type);
}
catch (Exception e)
{
throw e;
}
}

How can I post my data onto the server?

I am developing wp8 app. My question is that, The app is getting an error when I click on the registration button and the following exception occurred and the code is not going below string post data
An exception of type System.UnauthorizedAccessException occurred in System.Windows.ni.dll but was not handled in user code
If there is a handler for this exception, the program may be safely continue
namespace docapp
{
public partial class registration : PhoneApplicationPage
{
public static string DeviceIDAsString;
public registration()
{
InitializeComponent();
//selction.Items.Add("india");
//selction.Items.Add("pakistan");
//selction.Items.Add("china");
//selction.Items.Add("USA");
String[] name = { "india", "china", "pakistan" };
String[] uname = { "Delhi", "Bijing", "Karachi" };
String[] university = { "AIIMS", "MDU", "PGI" };
String[] yeardate = { "2011", "2012", "2013" };
string[] question = { "what is your pet name", "what is your childhood name", "what is your mother name" };
this.country.ItemsSource = name;
this.city.ItemsSource = uname;
this.university.ItemsSource = university;
this.year.ItemsSource = yeardate;
this.question.ItemsSource = question;
}
private void Image_Tap_1(object sender, System.Windows.Input.GestureEventArgs e)
{
if (txtusername.Text == "")
{
MessageBox.Show("enter the name");
}
else if (txtid.Text == "")
{
MessageBox.Show("enter valid id");
}
else if (txtpassword.Password == "")
{
MessageBox.Show("enter the password");
}
else if (txtconfirm.Password == "")
{
MessageBox.Show("enter the same password again ");
}
else if (txtemail.Text == "")
{
MessageBox.Show("enter the valid email id ");
}
else if (txtmobileno.Text == "")
{
MessageBox.Show("enter the valid 10 digit mobile no ");
}
if (txtpassword.Password != txtconfirm.Password)
{
MessageBox.Show("password doesnot match please enter same password");
}
SendPost();
//getDeviceId();
}
//private static String getDeviceId()
//{
// //byte[] id = (byte[])Microsoft.Phone.Info.DeviceExtendedProperties.GetValue("DeviceUniqueId");
// //return BitConverter.ToString(id).Replace("-", string.Empty);
// // get the unique device id for the publisher per device
//}
void SendPost()
{
byte[] myDeviceID = (byte[])Microsoft.Phone.Info.DeviceExtendedProperties.GetValue("DeviceUniqueId");
DeviceIDAsString = Convert.ToBase64String(myDeviceID);
Uri url = new Uri(" http://www.mobileoid2.co/docbase/index.php?methodname=createuser");
// Create the web request object
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Method = "POST";
webRequest.Headers["username"] = txtusername.Text;
webRequest.Headers["userid"] = txtid.Text;
webRequest.Headers["password"] = txtpassword.Password;
webRequest.Headers["confirmpaswword"] = txtconfirm.Password;
webRequest.Headers["email"] = txtemail.Text;
webRequest.Headers["mobileno"] = txtmobileno.Text;
webRequest.Headers["country"] = country.SelectedItem.ToString();
webRequest.Headers["city"] = city.SelectedItem.ToString();
webRequest.Headers["university"] = university.SelectedItem.ToString();
webRequest.Headers["year"] = year.SelectedItem.ToString();
webRequest.Headers["question"] = question.SelectedItem.ToString();
webRequest.Headers["uniqueid"] = DeviceIDAsString;
webRequest.ContentType = "application/json;charset=utf-8";
//"text/json";//
// Start the request
webRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), webRequest);
}
void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
// End the stream request operation
Stream postStream = webRequest.EndGetRequestStream(asynchronousResult);
string postData = "username" + txtusername.Text + ".userid" + txtid.Text + "." + ".password" + txtpassword.Password + "." + ".confirmpassword" + txtconfirm.Password + "." + ".email" + txtemail.Text + "." + ".mobileno" + txtmobileno.Text + "." + "." + ".country" + country.SelectedItem.ToString() + "." + "." + ".city" + city.SelectedItem.ToString() + "." + "." + ".university" + university.SelectedItem.ToString() + "." + "." + ".year" + year.SelectedItem.ToString() + "." + ".question" + question.SelectedItem.ToString() + "." + ".uniqueid" + DeviceIDAsString +".";
var input = JsonConvert.SerializeObject(postData);
byte[] byteArray = Encoding.UTF8.GetBytes(input);
// Add the post data to the web request
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
// Start the web request
webRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), webRequest);
}
void GetResponseCallback(IAsyncResult asynchronousResult)
{
try
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response;
// End the get response operation
response = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamReader = new StreamReader(streamResponse);
var Response = streamReader.ReadToEnd();
//outputbox.Text = Response.ToString();
streamResponse.Close();
streamReader.Close();
response.Close();
}
catch (WebException e)
{
// Error treatment
// ...
}
}
private void Image_Tap_2(object sender, System.Windows.Input.GestureEventArgs e)
{
NavigationService.Navigate(new Uri("/docapp;component/login.xaml", UriKind.RelativeOrAbsolute));
}
}
}
Not sure why, but this error is generally thrown when the access is not allowed. Maybe the credentials you are trying to use are not allowed!
The issue is that the OS is denying the request due to I/O error, where the credentials are required, or you either don't have permission to read/write there, or the server needs a username/password match to allow you. Something like that. Try catching it using
try {
// code here to try..
} catch (System.UnauthorizedAccessException e) {
// error e.Message
}
Here is a Remark from the MSDN blog post:
An UnauthorizedAccessException exception is typically thrown by a method that wraps a Windows API call. To find the reasons for the exception, examine the text of the exception object's Message property.
For More: http://msdn.microsoft.com/en-us/library/system.unauthorizedaccessexception(v=vs.110).aspx

530-5.5.1 Authentication required error, smtp

here is my FULL code below,Please need help, I have been trying to send email via gmail, I get this error "530-5.5.1 Authentication required", the exception occurs in the method called "Send()" on this line here: (see full code below), I am not using the c# library for some reason, so I need to get this to work, thanks.
//EXCEPTION OCCURS HERE, SEE THE SEND METHOD BELOW FOR FULL CODE
foreach (string address in to)
{
try
{
message = "RCPT TO:<" + address + ">\r\n";
response = ReadLine();
SendCommand(message);
Console.WriteLine(response);
if (response.Substring(0, 3) != "250")
{
throw new SmtpException(response);
}
}
}
//CONSTRUCTOR
public Smtp()
{
Port =465 ;
Host = "smtp.gmail.com";
Email = "email#gmail.com";
Password = "xxxxxxx";
to = new List<String>() { "reciever#gmail.com"};
from = "sender#gmail.com";
}
//FULLE CODE
public void Connect()
{
if (Client == null)
Client = new TcpClient();
if (!Client.Connected)
Client.Connect(Host, Port);
//if (IsSecure)
//{
SslStream secureStream =
new SslStream(Client.GetStream());
secureStream.AuthenticateAsClient(Host);
ClientStream = secureStream;
secureStream = null;
Console.WriteLine("secure");
//}
//else
//{
// ClientStream = Client.GetStream();
// Console.WriteLine("non secure");
//}
Writer = new StreamWriter(ClientStream);
Reader = new StreamReader(ClientStream);
string c= ReadLine();
Console.WriteLine(c);
string message = "EHLO me";
SendCommand(message);
string response = ReadLine();
Console.WriteLine(response);
if (response.Substring(0, 3) != "250")
{
// throw new SmtpException(response);
}
Send();
}
// public void
public void Send()
{
string message = "MAIL FROM:<" + Email + ">";
SendCommand(message);
string response = ReadLine();
Console.WriteLine(response);
if (response.Substring(0, 3) != "250")
{
throw new SmtpException(response);
}
string x = ReadLine();
Console.WriteLine(x);
**//EXCEPTION OCCURS HERE**
foreach (string address in to)
{
try
{
message = "RCPT TO:<" + address + ">\r\n";
response = ReadLine();
SendCommand(message);
Console.WriteLine(response);
if (response.Substring(0, 3) != "250")
{
throw new SmtpException(response);
}
}
catch (SmtpException e)
{
System.Console.WriteLine("{ 0}", e.Message);
}
}
message = "DATA\r\n";
SendCommand(message);
response = ReadLine();
Console.WriteLine(response);
if (response.Substring(0, 3) != "354")
{
throw new SmtpException(response);
}
message = "Subject: " + subject + "\r\n";
foreach (string address in to)
{
message += "To: " + address + "\r\n";
}
foreach (string address in cc)
{
message += "Cc: " + address + "\r\n";
}
message += "From: " + from + "\r\n";
if (bodyHtml.Length > 0)
{
message += "MIME-Version: 1.0\r\n"
+ " Content-Type: text/ html;\r\n"
+ " charset=\" iso-8859-1\"\r\n";
message += "\r\n" + bodyHtml;
}
else
{
message += "\r\n" + bodyText;
};
message += "\r\n.\r\n";
SendCommand(message);
response = ReadLine();
Console.WriteLine(response);
if (response.Substring(0, 3) != "250")
{
throw new SmtpException(response);
}
message = "QUIT\r\n";
SendCommand(message);
response = ReadLine();
Console.WriteLine(response);
if (response.IndexOf(" 221") == -1)
{
throw new SmtpException(response);
}
}
public void Close()
{
if (Client != null)
{
if (Client.Connected)
Logout();
Client.Close();
Client = null;
}
if (ClientStream != null)
{
ClientStream.Close();
ClientStream = null;
}
if (Writer != null)
{
Writer.Close();
Writer = null;
}
if (Reader != null)
{
Reader.Close();
Reader = null;
}
disposed = true;
}
public void Dispose()
{
if (!disposed)
Close();
}
protected void Login()
{
if (!IsResponseOk(SendCommand("USER " + Email)) ||
!IsResponseOk(SendCommand("PASS " + Password)))
throw new Exception("User/password not accepted");
}
protected void Logout()
{
SendCommand("RSET");
//SendCommand("QUIT");
}
protected string SendCommand(string cmdtext)
{
Writer.WriteLine(cmdtext);
Writer.Flush();
return ReadLine();
}
protected string ReadLine()
{
return Reader.ReadLine() + "\r\n";
}
protected string ReadLines()
{
StringBuilder b = new StringBuilder();
while (true)
{
string temp = ReadLine();
if (temp == ".\r\n" || temp.IndexOf("-ERR") != -1)
break;
b.Append(temp);
}
return b.ToString();
}
protected static bool IsResponseOk(string response)
{
if (response.StartsWith("+OK"))
return true;
if (response.StartsWith("-ERR"))
return false;
throw new Exception("Cannot understand server response: " +
response);
}
Clearly the SMTP server requires authentication before accepting mail to send. This is commonplace as spammers and scammers used to use 'open relays' to peddle their wares.
Check the rules for the server to see what authentication they will accept. The Wikipedia reference at http://en.wikipedia.org/wiki/SMTP_Authentication might be useful.

inefficient to efficient way to create subfolder in FTP

I was using Make directory to create a folders and subfolder in my ftp (using filezilla) works fine,but when i try to do in my test server (IIS FTP) doesn't work ,throws 550,file not found or no access.so just a quick way to change the code to create subdirctory in my ftp server works fine but i know its a kinda shitty way to do like that.
Changed my code based on #Markus
var dir = new ConsoleApplication5.Program();
string path = "ftp://1.1.1.1/testsvr01/times/" + "testfile" + "/svr01fileName";
string[] pathsplit = path.ToString().Split('/');
string Firstpath = pathsplit[0] + "/" + pathsplit[1] + "/" + pathsplit[2] + "/" + pathsplit[3] + "/";
string SecondPath = Firstpath + "/" + pathsplit[4] + "/";
string ThirdPath = SecondPath + "/" + pathsplit[5] + "/";
string[] paths = { Firstpath, SecondPath, ThirdPath };
foreach (string pat in paths)
{
bool result= dir.EnsureDirectoryExists(pat);
if (result==true)
{
//do nothing
}
else
{ //create dir
dir.createdir(pat);
}
}
upload(path,filename);
}
private bool EnsureDirectoryExists(string pat)
{
try
{
//call the method the first path is exist ?
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(pat);
request.Method = WebRequestMethods.Ftp.ListDirectory;
request.Credentials = new NetworkCredential("sh", "se");
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
{
return true;
}
}
catch (Exception ex)
{ return false; }
}
public void createdir(string pat)
{
try
{
FtpWebRequest createdir = (FtpWebRequest)FtpWebRequest.Create(new Uri(pat));
createdir.Method = WebRequestMethods.Ftp.MakeDirectory;
createdir.Credentials = new NetworkCredential("sh", "se");
createdir.UsePassive = true;
createdir.UseBinary = true;
createdir.KeepAlive = false;
FtpWebResponse response1 = (FtpWebResponse)createdir.GetResponse();
Stream ftpStream1 = response1.GetResponseStream();
ftpStream1.Close();
response1.Close();
}
catch (Exception ex)
{
}
}
Please if any of you guys find a better way,suggest me.
That's a lot of code for ensuring a directory exists. Is there a Directory.Exists() method (or a similar method you could leverage)? Then you could call an EnsureDirectoryExists() before uploading.
private bool EnsureDirectoryExists(string path)
{
// check if it exists
if (Directory.Exists(path))
return true;
string parentPath = GetParentPath(path);
if (parentPath == null)
return false;
bool result = EnsureDirectoryExists(parentPath);
if (result)
{
CreateDirectory(path);
return true;
}
return false;
}
Disclaimer: You might need to tweak the logic a bit and use the FTP functions, but I hope you get the point.

Process.Start Catch all FileName/Arguments code

I have some code that I wanted to improve. It uses Process.Start and should be able to handle any input any argument, and still work.
I don't think I have covered all the bases. Can anyone suggest a better/more thorough approach?
ToMaybeUri is an extension method that tries to create a Uri.
ToValidMailToArgument is an extension method that adds "attachments="
IsValidEmail is an extension method that does a RegEx on the email address.
public static void RunProcess(string fileName, string Params)
{
var useProcessStart = true;
var validFile = false;
var validDir = false;
var validEmail = false;
var validURL = false;
var proc = new Process();
var info = new ProcessStartInfo(fileName);
info.UseShellExecute = true;
info.Arguments = Params;
//try catches here in case the syntax of the string has invalid characters for dir/file
try
{
var di = new DirectoryInfo(fileName);
validDir = di == null ? false : di.ExistsNow();
}
catch (Exception ex) { }
try
{
var fi = new FileInfo(fileName);
validFile = fi == null ? false : fi.Exists();
}
catch (Exception ex) { }
if (Params == "")
{
if (validFile)
{
if (Path.GetExtension(fileName).ToUpper() == ".CHM")
{
var helpProvider1 = new HelpProvider();
helpProvider1.HelpNamespace = fileName;
Help.ShowHelp(Application.OpenForms[0], helpProvider1.HelpNamespace);
MessageBox.Show(msg);
return;
}
}
else if (validDir)
{
//skip
}
else if (fileName.IsValidEmail())
{
validEmail = true;
info.FileName = "mailto:" + info.FileName;
info.Arguments = "";
}
else if (fileName.IsValidUrl())
{
validURL = true;
info.FileName = fileName.ToMaybeUri().Value.ToString();
info.Arguments = "";
}
else
{
MessageBox.Show(fileName + " does not exist.");
}
}
else
{
//and has params
if (Path.GetExtension(fileName).ToUpper() == ".PDF" && Params.ToLower().StartsWith("p"))
{
int pageNum = 0;
string pageNumString = Grazer.Utilities.Strings.Right(Params, Params.Length - 1);
int.TryParse(pageNumString, out pageNum);
//PDFLocation = "/A \"page=" + pageNum + "=OpenActions\" \"" + ssGlobals.ssStartDir + "\\Example.pdf\""
string app = GrRegistry.GetApplicationFromExtension(".PDF");
if (Path.GetFileNameWithoutExtension(app).ToUpper() == "ACROBAT" || Path.GetFileNameWithoutExtension(app).ToUpper() == "ACRORD32")
{
string PDFLocation = String.Format("/A \"page={0}=OpenActions\" \"{1}\"", pageNum, Path.GetFullPath(fileName));
info = new ProcessStartInfo(app);
info.Arguments = PDFLocation;
}
}
else if (fileName.IsValidEmail())
{
validFile = false;
try
{
var fi = new FileInfo(info.Arguments);
validFile = fi == null ? false : fi.ExistsNow();
}
catch (Exception ex) { }
info.FileName = String.Format("mailto:{0}{1}", fileName, new FileInfo(info.Arguments).ToValidMailToArgument());
info.Arguments = "";
}
}
if (useProcessStart)
{
proc.StartInfo = info;
try
{
if (validURL || validFile || validDir || validEmail)
proc.Start();
}
catch (Exception ex)
{
switch (ex.Message)
{
case "No process is associated with this object.":
break;
default:
MessageBox.Show(ex);
if (info.Arguments.ToEmptyIfNull().Length > 0)
MessageBox.Show(String.Format("{0} could not be opened with parameters: {1}", info.FileName, info.Arguments));
else
MessageBox.Show(String.Format("{0} could not be opened", info.FileName));
break;
}
}
}
}
To start with, you don't want to swallow exceptions. On your catch blocks, make sure you're doing something after catching an exception. Also, find out what specific exceptions can be thrown by methods you're calling in your try blocks and catch those specific exceptions, like so:
try
{
SomeMethod();
}
catch (SpecificExceptionType1)
{
//do something based on what this exception means
}
catch (SpecificExceptionType2)
{
//ditto here
}
catch
{
//handle unexpected exceptions here
}
Also, this smells suspiciously like homework - perhaps implementing a command shell? If so, retag it as homework. If not, just tell me to stuff it.

Categories

Resources