|
When I rename the file that the code below is trying to open, I would expect an exception to be thrown(according to MSDN documentation). However, no exception is thrown and sr == null. Can anybody show me what I may be missing here?
StreamReader sr = null;
try
{
sr = File.OpenText(strFileName);
}
catch(System.IO.FileNotFoundException)
{
listBoxErrors.Items.Add("Unable to locate upload file.");
}
catch(Exception ex)
{
listBoxErrors.Items.Add("general error.");
}
Thanks,
Craig
Craig
|
|
|
|
|
You're not getting an exception because you are not trying to catch the correct exception. Using FileNotFoundException will throw an exception when a file you attempt to access doesn't exist. Replace your catch with the one below and it should work.
<br />
catch(FileNotFoundException ex)<br />
{<br />
listBoxErrors.Items.Add("general error.");<br />
}</
I get all the news I need from the weather report - Paul Simon (from "The Only Living Boy in New York")
|
|
|
|
|
I am trying to catch the FileNotFoundException so I don't what your talking about. Look closer at my code sample. Have you ever tried this yourself. It seems to me that I should get a FileNotFoundException but that's not my experience.
Craig
|
|
|
|
|
No, I haven't tried this myself. Did you try using the code snippet I provided? Your are trying to catch a general Exception. No general exception is going to be produced if the file doesn't exist, you need to catch the FileNotFoundException.
I didn't actually read your code completely, but I thought I did. I tested the below code and it worked just fine.
System.IO.StreamReader sr = null;<br />
try<br />
{<br />
sr = System.IO.File.OpenText(@"C:\Data.txt");<br />
}<br />
catch (System.IO.FileNotFoundException)<br />
{<br />
MessageBox.Show("Unable to locate upload file.");<br />
}<br />
catch (Exception ex)<br />
{<br />
MessageBox.Show("general error.");<br />
}
-- modified at 16:28 Thursday 16th August, 2007
I get all the news I need from the weather report - Paul Simon (from "The Only Living Boy in New York")
|
|
|
|
|
I see my mistake. I should have been returning after catching the exception. I was only reporting it and hence the procedure would continue and try to open up the file. But to correct your last statement "no general exception is going to be produced if the file doesn't exist, you need to catch the FileNotFoundException" this isn't true.
FileNotFoundException is the more specific exception and if a catch for this is not specified, the general exception would be caught. If you look at my code sample you will see that I was filtering down to the more general exception in case some other type of unknown exception occurred.
Thanks for taking the time to exchange some ideas. I spaced and I don't have any other software people here to bounce thoughts off of.
I need another cup of coffee,
Craig
Craig
|
|
|
|
|
Interestingly enough, I have just had the same issue that you were having. How did you correct for this?
CTaylor89 wrote: I should have been returning after catching the exception. I was only reporting it and hence the procedure would continue and try to open up the file.
I don't get what that means though
I get all the news I need from the weather report - Paul Simon (from "The Only Living Boy in New York")
|
|
|
|
|
All I was trying to say was that in my exception handler I was only putting up a message box to report the exception. What I forgot to put in the exception handler was a return statement so that I would not continue executing in the current function trying to execute code that depended on the file being open.
Craig
|
|
|
|
|
Hi there,
More questions!!!
I need to know how I can obtain the number of files in a directory programmaticaally (including files in sub folders). Well, I can do this by getting the directory list, and recursively getting the file list in them and have a variable to increment. But, i wonder whether there is a more straightforward method.
Secondly, I need to know of a procedure to get the file size of a file through C# coding.
Regards,
A
|
|
|
|
|
The relevant classes are File, FileInfo, Directory, DirectoryInfo
they are fully explained in the MSDN documentation.
Luc Pattyn [Forum Guidelines] [My Articles]
this weeks tips:
- make Visual display line numbers: Tools/Options/TextEditor/...
- show exceptions with ToString() to see all information
- before you ask a question here, search CodeProject, then Google
|
|
|
|
|
Hey folks. Not sure if this belongs here but it seems to me it's more of a C# thing than an SQL thing.
I'm writing a reporting program for the high school I work for, to allow teachers to write reports with pre-defined statements. We already have one in place that's written with Access, but it's a PITA and needs replacing, hence me breaking out the C#.
Now I'm amateurish at best (I'm IT Support, not a programmer for starters), so lets get that out of the way!
I'm using Castle ActiveRecord to let me do ORM and handle my database for me. I have four Achievement tables and 3 Target tables and they all have the same layout (schema?) of (Id, Subject, Comment, YearGroup) - so we have tables in the db called Achieve1 - Achieve4, and Target1 - Target3.
Since each table has to be managed with a corresponding class for ActiveRecord, I created a base abstract class that the other tables could inherit from and initialise ActiveRecord against...
Wow, I'm explaining this crappily - here is some code instead to illustrate:
abstract class AchieveTargetBase : ActiveRecordBase
{
private int _id;
private Subject _subject;
private string _comment;
private int _yeargroup;
[PrimaryKey]
public int Id
{
get { return _id; }
set { _id = value; }
}
[BelongsTo("Subject")]
public Subject Subject
{
get { return _subject; }
set { _subject = value; }
}
[Property(Length=400)]
public string Comment
{
get { return _comment; }
set { _comment = value; }
}
[Property]
public int YearGroup
{
get { return _yeargroup; }
set { _yeargroup = value; }
}
}
And then I do...
[ActiveRecord("Achieve1")]
class Achievement1 : AchieveTargetBase
{
}
And so on, per table, which works fine.
Now the problem I have is with writing classes that I need to use on each table, because I need to reference the class itself. As an example, if I were to write code that retrieves the comment text of selected rows for Achieve1
[ActiveRecord("Achieve1")]
class Achievement1 : AchieveTargetBase
{
public static string[] GetListOfEntries(Subject subj, int year)
{
List<string> Entries = new List<string>();
foreach (Achievement1 x in (Achievement1[])ActiveRecordBase.FindAll(typeof(Achievement1), Expression.Eq("Subject", subj), Expression.Eq("YearGroup", year)))
{
Entries.Add(x.Comment);
}
string[] ret = Entries.ToArray();
Array.Sort(ret);
return ret;
}
}
I've tried replacing Achievement1 in the foreach argument with AchieveTargetBase and putting it into the AchieveTargetBase class instead but that just throws up an error (which I expected, to be honest).
Is there any way I can make methods like that apply for each class without having to write it separately for each of the derived classes?
Disclaimer: I'm a n00bish programmer. Please be gentle. (Especially if the answer is dead easy cos it'll just make me feel stupid.
-- modified at 6:02 Friday 17th August, 2007
|
|
|
|
|
Your base class does not need to be pure abstract, you can have common function in it that all derived classes can use.
only two letters away from being an asset
|
|
|
|
|
Basically it seems you are having trouble getting the type in the abstract base class.
Try something like:
foreach (AchieveTargetBase x in (AchieveTargetBase[])ActiveRecordBase.FindAll(this.GetType(), Expression.Eq("Subject", subj), Expression.Eq("YearGroup", year)))
|
|
|
|
|
Basically it seems you are having trouble getting the type in the abstract base class.
That's the problem, yes. (And for some reason I couldn't just sum it up like that yesterday - I was tired!)
I tried the code you suggested first, in the AchieveTargetBase class, but it doesn't work because I'm not initialising ActiveRecord against that class (as I want that class as a base for the others, not an actual ActiveRecord class/table).
Would using this work? That's probably a rhetorical question since I'll try it in a few minutes when I've finished my current task.
|
|
|
|
|
I solved it using a generic class.
----------------------------------------------------------
public class GetListOfEntries<T> : ActiveRecordBase where T : AchieveTargetBase
{
private Subject _subj;
private int _year;
public GetListOfEntries(Subject subj, int year)
{
_subj = subj;
_year = year;
}
public string[] ReturnListOfEntries()
{
List<string> Entries = new List<string>();
foreach (T x in (T[])ActiveRecordBase.FindAll(typeof(T), Expression.Eq("Subject", _subj), Expression.Eq("YearGroup", _year)))
{
Entries.Add(x.Comment);
}
string[] ret = Entries.ToArray();
Array.Sort(ret);
return ret;
}
}
----------------------------------------------------------
Which works great.
Thanks for the help.
|
|
|
|
|
Hey all,
I've been given some fairly whiffy code to update, which I'm going to port over to C#. The port is going very well, but I have an architectural-type question which I hope you guys can help with.
The original developer was clearly a fan of the VB's select-case statement; the app isn't very big, but so far I've found at least 50 seperate instances of this flow control structure (some of which are clearly copied and pasted). Whilst I can quite easily refactor some of the concepts into objects, there is one area I'm not to sure about.
One part of the program reads data in from a file, and depending on the value read in, decides on a course of action. The decision is made by a slect case statement, which to my mind adds fragility to the application as it's probable that more value/decision pairs will need to be made. (Actually, this must have happened to the original developer on seperate occasions, as there are over 70 cases which the comments suggest were added over time!)
Given this, are there any recommended patterns I could look to implement instead of replicating the switch case in my code?
"It was the day before today.... I remember it like it was yesterday."
-Moleman
|
|
|
|
|
First a few questions:
What kind of file is it? I'm guessing a flat file with multiple distinct data segments?
Are there any common elements to each of the data segments?
Is this a forward only read?
I'm largely language agnostic
After a while they all bug me
|
|
|
|
|
It's a bit of a duff system, to be honest, but basically El Supremo (the original dev) has created what he terms a "transport mechanism" - it's not really - and it goes something like this:
He takes a plain ordinary text file, and writes in it some header information such as:
original path = C:\test.txt
output path = z:\test.txt
creation date = blah blah blah
Then after this "header" has been defined, he writes all the bytes of the original file - whatever it is. Finally, he inserts the length of the file (in bytes) before the header. So in the finished article you get something like this:
15465
original path = C:\test.txt
output path = z:\test.txt
creation date = blah blah blah
A whole bunch of bytes go here.
The killer is that the header can appear in any order whatsoever and some things are optional (except that the length of the file always appears before it). To actually extract the data I calculate the length of the file, minus the length of the data bytes to get to the first byte of the data.
Man, perhaps I should put this into Coding Horrors
"It was the day before today.... I remember it like it was yesterday."
-Moleman
|
|
|
|
|
Hi Martin,
if the header lines are just a distraction, I don't see why you would bother
to provide a switch or some fancy patterns, just skip it the way you described.
Luc Pattyn [Forum Guidelines] [My Articles]
this weeks tips:
- make Visual display line numbers: Tools/Options/TextEditor/...
- show exceptions with ToString() to see all information
- before you ask a question here, search CodeProject, then Google
|
|
|
|
|
I think you're probably right (either that, or I should get a new job!)
"It was the day before today.... I remember it like it was yesterday."
-Moleman
|
|
|
|
|
That's truely ugly, I doubt there's a clean way of parsing that, typical situation where you end up with the MOASS (Mother Of All Switch/Select Statements) Ignore what you can me thinks.
I'm largely language agnostic
After a while they all bug me
|
|
|
|
|
I'd look into a mixture of the Factory Idiom and the Strategy Design Pattern.
Basically, one method (factory method) takes the argument that would be used as the Select Case argument and returns the correct "strategy", which are implementations of a simple interface (IStrategy.Execute() could be your only method in the interface. The factory creates the right strategy based on the the value read in the file and returns the reference to the interface.
|
|
|
|
|
martin_hughes wrote: One part of the program reads data in from a file, and depending on the value read in, decides on a course of action. The decision is made by a slect case statement
Actually, this is one of those places where a select statement is appropriate. When reading raw data from a file, you are at the boundary of your application. As such, the data doesn't represent objects that you can manipulate, so you are forced to use conditionals to decide what to do. Usually, the course of action is to create an object to encapsulate the data. From there, the rest of the application deals with the object(s) rather than the raw data, and you can design your classes in such a way as to take advantage of polymorphism. But at the boundary of your application, you need a way to interpret the data and transform it into objects. switch/select statements are fine for this.
Now having said all of that, if you can figure out a way to serialize the data to file so that it can be deserialized directly into objects by your environment, then cool. Otherwise, don't be bothered by the switch/select statements.
All my opinion, of course. 
|
|
|
|
|
Greetings,
Below code would do the following upon user clicks the button:
if user clicks on a specific cell on the instantiated form's datagridview, the appropriate row's data is copied into the caller form's datagridview.
Problem is: the anonym method is fired as many times as user clicks "this" form's button (in order to show up the other form, whose datagridview contains the data to be copied onto "this" form' gridview) BUT I'd like it to be fired only ONCE at a time. thanks for any thread, g (placing "return" didn't help)
<br />
public int I = 0;<br />
private void btnHozzaadas_Click(object sender, EventArgs e)<br />
{<br />
Guid[] array = new Guid[15];<br />
<br />
<br />
<br />
tetelArErAnSzerk.Owner = this;<br />
<br />
tetelArErAnSzerk.anyagDataGridView.CellClick += delegate<br />
{<br />
<br />
if (tetelArErAnSzerk.anyagDataGridView.CurrentCell.OwningColumn.DataPropertyName == "AnyagHozzaadas")<br />
{<br />
<br />
DataView datatableView = felhasznAnyagSzallitasBindingSource.List as DataView;<br />
DataRowView rowView = datatableView.AddNew();<br />
<br />
Debmut9DataSet.Felhaszn_AnyagSzallitasRow felhasznaltanyagdatarow = (felhasznaltanyagszallitasDataGridView.Rows[I].DataBoundItem as DataRowView).Row<br />
as Debmut9DataSet.Felhaszn_AnyagSzallitasRow;<br />
<br />
rowView["TetelArId"] = (tetelArBindingSource.Current as DataRowView)["TetelArId"];<br />
felhasznaltanyagdatarow.AnyagId = new Guid();<br />
Guid anyagid = ((tetelArErAnSzerk.anyagDataGridView.CurrentRow.DataBoundItem as DataRowView).Row as<br />
Debmut9DataSet.AnyagRow).AnyagId;<br />
array[I] = anyagid;<br />
if (I == 0)<br />
<br />
{ felhasznaltanyagdatarow.AnyagId = anyagid; }<br />
<br />
<br />
if (I > 0)<br />
{<br />
for (int J = 0; J < felhasznaltanyagszallitasDataGridView.Rows.Count - 1; J++)<br />
{<br />
<br />
for (int K = 1; K < felhasznaltanyagszallitasDataGridView.Rows.Count - 1; K++)<br />
{<br />
if (J == K)<br />
{<br />
K++;<br />
}<br />
if (array[J] == array[K])<br />
{<br />
MessageBox.Show("Component exists, Cant be added again!", "Not added...", MessageBoxButtons.OK, MessageBoxIcon.Warning);<br />
felhasznAnyagSzallitasBindingSource.Remove(rowView);<br />
<br />
<br />
return;<br />
}<br />
<br />
}<br />
<br />
<br />
}<br />
}<br />
<br />
felhasznaltanyagdatarow.AnyagId = anyagid;<br />
<br />
felhasznaltanyagszallitasDataGridView.Rows[I].Cells["Anyagszallfelhaszn_Megnevezes"].Value = ((tetelArErAnSzerk.anyagDataGridView.CurrentRow.DataBoundItem as DataRowView).Row as<br />
Debmut9DataSet.AnyagRow).AnyagNev;<br />
felhasznaltanyagszallitasDataGridView.Rows[I].Cells["Anyagszallfelhaszn_Szall_szolg"].Value = ((tetelArErAnSzerk.anyagDataGridView.CurrentRow.DataBoundItem as DataRowView).Row as<br />
Debmut9DataSet.AnyagRow).AnyagSzallito;<br />
felhasznaltanyagszallitasDataGridView.Rows[I].Cells["Anyagszallfelhaszn_Me"].Value = tetelArErAnSzerk.anyagDataGridView.CurrentRow.Cells["Anyag_Me"].FormattedValue;<br />
felhasznaltanyagszallitasDataGridView.Rows[I].Cells["Anyagszallfelhaszn_ear"].Value = ((tetelArErAnSzerk.anyagDataGridView.CurrentRow.DataBoundItem as DataRowView).Row as<br />
Debmut9DataSet.AnyagRow).AnyagBer;<br />
egysegar[I] = ((tetelArErAnSzerk.anyagDataGridView.CurrentRow.DataBoundItem as DataRowView).Row as<br />
Debmut9DataSet.AnyagRow).AnyagBer;<br />
felhasznAnyagSzallitasBindingSource.MoveLast();<br />
<br />
felhasznaltanyagszallitasDataGridView.Refresh();<br />
I++;<br />
MessageBox.Show("Added successfully", "Added...", MessageBoxButtons.OK, MessageBoxIcon.Information);<br />
return;<br />
}<br />
};<br />
tetelArErAnSzerk.Show();<br />
}<br />
|
|
|
|
|
Hi,
your code is hard to read without indentation, with long lines, etc.
better is to use CODE PRE tags.
I think the problem is every time you click the button, a delegate is ADDED
to the DGVcell; you should do this only once.
You may want to read my article on events (and the one on CodeRescue).
-- modified at 17:42 Thursday 16th August, 2007
Luc Pattyn [Forum Guidelines] [My Articles]
this weeks tips:
- make Visual display line numbers: Tools/Options/TextEditor/...
- show exceptions with ToString() to see all information
- before you ask a question here, search CodeProject, then Google
|
|
|
|
|
Hi Luc,
Thanks for your post
Gonna go & read your article. Cheers
|
|
|
|
|