FileStream Question

  • Thread starter Thread starter ewingate
  • Start date Start date
E

ewingate

The following code which is supposed to dynamically create files with
incrementing names is throwing an exception due to the inclusion of the
DateTime.Now component of the sReportSave string:

string sReportSave = ( DateTime.Now + "Report.Dat" );
FileStream fs = new FileStream( sReportSave , FileMode.Create );

Is my approach completely wrong or is there different way to modify the
FileStream so that .NETclients used by multiple users could save files
incrementally without saving to the same file? The logic that I would
normally use for this sort of thing seems unsuitable due to the fact
that I am trying to make the clients run independantly of each other
even if used on the same machine.

-E
 
You want to specify a pattern for the time, especially if you'll be
using the value in a filename (slashes are not valid in a file name).

DateTime.Now.ToString("yyyy-MM-dd--HH-mm-ss-") + "Report.dat"

But you have to be concerned with multiple clients making the file at
the same time so you may want to include a counter within a loop and
error checking:


int i = 1;
bool alreadyUsed = false;
FileStream fs;
do {
string name = null;
try {
name =
String.Format("{0:yyyy-MM-dd--HH-mm-ss}--{1:000}-Report.dat",
DateTime.Now, i++);
fs = new FileStream(name, FileMode.Create);
} catch(IOException ex) {
if (File.Exists(name)) {
alreadyUsed = true;
} else {
throw;
}
}
} while(alreadyUsed);


If you think the likihood of two processes creating the same file is
high then you can check File.Exists before trying to create the file
to be more efficient, but you still need the error handling since
another process could create the file between your File.Exists call
and the new FileStream call.

HTH,

Sam
 
Thank you! That is precisely what I needed to know. Thank you very much
for your assistance.

-E
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top