Ok I tested this and it work. I've refactored everything and made it easier to understand.
Here's the base code-block that you posted. See, I've simplified it a bit by putting the creation of the Excel file into another function. Note that I've also used
templatePath
and
filePath
instead of creating them on the fly all the time.
CreateExcelFile(templatePath, filePath);
try
{
StreamWriter sSW = new StreamWriter(filePath, true);
sSW.AutoFlush = true;
foreach(object item in exHistListBox1.SelectedItems)
{
string itemStr = item.ToString();
sSW.Write("\n" + CleanString(itemStr));
}
sSW.Close();
}
catch(FileNotFoundException err)
{
System.Diagnostics.Debug.WriteLine(err.Message);
}
I think the main problem of your code was the
Do...Loop
. I've simplified it a bit by using a
foreach
.
Here's the code for the two subfunction.
private static string CleanString(string StringToClean)
{
string result = StringToClean;
while(result.IndexOf(" ") >= 0)
{
result = result.Trim();
result = result.Replace("\t", ",");
result = result.Replace(" ", ",");
result = result.Replace(",,", ",");
}
System.Diagnostics.Debug.WriteLine("String cleaned result: " + result);
return result;
}
private static void CreateExcelFile(string templatePath, string filePath)
{
if(File.Exists(templatePath))
{
if(!File.Exists(filePath))
{
File.Copy(templatePath, filePath, false);
System.Diagnostics.Debug.WriteLine(DateTime.Now + " : EXCEL FILE CREATED, loc- " + filePath);
}
else
{
System.Diagnostics.Debug.WriteLine(DateTime.Now + " : EXCEL FILE ALREADY EXISTED, loc- " + filePath);
}
}
else
{
throw new FileNotFoundException("Template.xlt was not found");
}
}
I've buffed you file copy algorithm. Now, it checks if the files exists before copying. If the template don't exist, you'll get an error message instead of an exception.
Test it and if it doesn't work, don't hesitate to comment and we'll try to fix things up.