How to prevent empty file from being created - c#

I have a file that is being created based on the items in a Repeater control if the radioButton for each item is "Yes". My issue that if the file is empty, it is still being created. I have tried FileName.Length > 0 and other possible solutions but I get errors that the file can not be found. I am sure the issue is within my logic but I cant see where. Any ideas?
protected void btnContinue_Click(object sender, EventArgs e)
{
string JobName;
string FileName;
StreamWriter sw;
string Name, Company, Date;
JobName = TYest + "_" + System.DateTime.Now;
JobName = JobName.Replace(":", "").Replace("/", "").Replace(" ", "");
FileName = JobName + ".txt";
sw = new StreamWriter(C: +"/" + FileName, false, Encoding.GetEncoding(1250));
foreach ( RepeaterItem rpItems in rpGetData.Items )
{
RadioButtonList rbYesNo = (RadioButtonList)rpItems.FindControl("rbBadge");
if ( rbYesNo.SelectedItem.Text == "Yes" )
{
Label rName = (Label)rpItems.FindControl("lblName");
Label rCompany = (Label)rpItems.FindControl("lblCompany");
Label rFacilityName = (Label)rpItems.FindControl("lblFacility_Hidden");
Name = rName.Text;
Company = rCompany.Text;
Date = System.DateTime.Now.ToString("MM/dd/yyyy");
sw.WriteLine("Name," + Name);
sw.WriteLine("Company," + Company);
sw.WriteLine("Date," + Date);
sw.WriteLine("*PRINTLABEL");
}
sw.Flush();
sw.Dispose();
if ( File.Exists("C:/" + FileName) )
{
try
{
File.Copy(+"C:/" + FileName, LoftwareDropPath + FileName, true);
}
catch ( Exception ex )
{
string msgE = "Error";
msgE += ex.Message;
throw new Exception(msgE);
}
}
else
{
//Do something if temp file not created properly
lblMessage.Text = "An error has occurred. Plese see your host to get a printed name badge.";
}
MessageBox messageBox = new MessageBox();
messageBox.MessageTitle = "Printed?";
messageBox.MessageText = "If not, please see host.";
Literal1.Text = messageBox.Show(this);
}
}

sounds like you want to detect if a file is empty. Use:
long length = new System.IO.FileInfo(path).Length;
if(length == 0)....
FileName.Length just tells you how long the file name is - not usefule

Why not check if the file exists first? That should solve your exception problems! If you want to know if the file is empty I would recommend checking what you're writing to the file and making sure it's not all empty and THEN write to the file if you actually have content?
if(File.Exists(File))
{
if(new FileInfo(File).Length > 0)
{
//Do Stuff.
}
}

How about this:
StreamWriter sw = null;
string Name, Company, Date;
JobName = TYest + "_" + System.DateTime.Now;
JobName = JobName.Replace(":", "").Replace("/", "").Replace(" ", "");
FileName = #"C:\" + JobName + ".txt";
try
{
foreach (RepeaterItem rpItems in rpGetData.Items)
{
RadioButtonList rbYesNo = (RadioButtonList)rpItems.FindControl("rbBadge");
if (rbYesNo.SelectedItem.Text == "Yes")
{
if (null == sw)
sw = new StreamWriter(FileName, false, Encoding.GetEncoding(1250));
Label rName = (Label)rpItems.FindControl("lblName");
Label rCompany = (Label)rpItems.FindControl("lblCompany");
Label rFacilityName = (Label)rpItems.FindControl("lblFacility_Hidden");
Name = rName.Text;
Company = rCompany.Text;
Date = System.DateTime.Now.ToString("MM/dd/yyyy");
sw.WriteLine("Name," + Name);
sw.WriteLine("Company," + Company);
sw.WriteLine("Date," + Date);
sw.WriteLine("*PRINTLABEL");
}
}
finally
{
if (null != sw)
{
sw.Flush();
sw.Dispose();
}
}
Build your FileName completely once so that you know it is always the same. Then only create your StreamWriter if something is going to be written. Also, use a try..finally to make sure your code to free your resources is always hit.

You should change it to only write and create the file when you have some data to write.
A simple way of doing this is to store everything memory with something like a StringBuilder, then afterwards write the contents of the string builder to the file if there is something to write:
var sb = new StringBuilder();
foreach (RepeaterItem rpItems in rpGetData.Items)
{
RadioButtonList rbYesNo = (RadioButtonList)rpItems.FindControl("rbBadge");
if (rbYesNo.SelectedItem.Text == "Yes")
{
// ..omitted..
sb.AppendLine("Name," + Name);
sb.AppendLine("Company," + Company);
sb.AppendLine("Date," + Date);
sb.AppendLine("*PRINTLABEL");
}
}
if (sb.Length > 0)
{
File.WriteAllText(FileName, sb.ToString(), Encoding.GetEncoding(1250));
}

You can check whether any items are eligible for saving before opening the stream writer like this:
var itemsToBeSaved = rpGetData.Items
Where(ri => ((RadioButtonList)ri.FindControl("rbBadge")).SelectedItem.Text == "Yes");
if (itemsToBeSaved.Any()) {
string path = #"C:\" + FileName;
using (var sw = new StreamWriter(path, false, Encoding.GetEncoding(1250))) {
foreach (RepeaterItem rpItems in itemsToBeSaved) {
Label rName = (Label)rpItems.FindControl("lblName");
Label rCompany = (Label)rpItems.FindControl("lblCompany");
Label rFacilityName = (Label)rpItems.FindControl("lblFacility_Hidden");
Name = rName.Text;
Company = rCompany.Text;
Date = System.DateTime.Now.ToString("MM/dd/yyyy");
sw.WriteLine("Name," + Name);
sw.WriteLine("Company," + Company);
sw.WriteLine("Date," + Date);
sw.WriteLine("*PRINTLABEL");
}
} // Flushes, Closes und Disposes the stream automatically.
}
The first statement prepares a filtered enumeration of repeater items containing only the ones to be saved. itemsToBeSaved.Any() tests if this enumeration contains at least one item. This enumeration is then reused in the foreach statement. Therefore it is not necessary to check the conditions again.
The using statement takes care of closing the stream in all situations, even if an exception should occur while writing to the file. I also declared the stream writer in the using statement. Therefore you can delete your declaration StreamWriter sw = null;.
Also note the expression #"C:\" + FileName. The # makes the string constant a verbatim string. This means that the usual escape character '\' loses its meaning and is used as is. Path.Combine(...) does not work here, since it does not add the path separator after a drive letter.

Related

Every time writes new file in c#

I am working on a c# console application. I am saving some data into a text file. Every time the programs are run it saves the data into that file without overwriting into it. Now I want to save the data into a new file every time I send a request/runs the new program.
var result = XmlDecode(soapResult);
XDocument doc = XDocument.Parse(result);
XmlReader read = doc.CreateReader();
DataSet ds = new DataSet();
ds.ReadXml(read);
read.Close();
if (ds.Tables.Count > 0 && ds.Tables["Reply"] != null && ds.Tables["Reply"].Rows.Count > 0)
{
string refNo = string.Empty;
string uniqueKey = string.Empty;
string meterNo = string.Empty;
List<string> ls = new List<string>();
if (ds.Tables["Reply"].Rows[0][0].ToString().ToUpper() == "OK")
{
if (ds.Tables["Names"] != null && ds.Tables["Names"].Rows.Count > 0)
{
uniqueKey = ds.Tables["Names"].Rows[0]["name"].ToString();
}
if (ds.Tables["NameType"] != null && ds.Tables["NameType"].Rows.Count > 0)
{
refNo = ds.Tables["NameType"].Rows[0]["name"].ToString();
}
if (ds.Tables["Meter"] != null && ds.Tables["Meter"].Rows.Count > 0)
{
if (ds.Tables["Meter"].Columns.Contains("mRID"))
{
meterNo = ds.Tables["Meter"].Rows[0]["mRID"].ToString();
processedRec++;
}
}
}
log = uniqueKey + " | " + refNo + " | " + meterNo + " | " + Environment.NewLine;
ls.Add(log);
}
File.AppendAllText(filePath, log);
How can I create a new file every time?
Any help would be highly appreciated.
Make a unique filePath. Something like this:
var filePath =$"{folderPath}\txtFile_{Guid.NewGuid()}";
This will make the file to be always unique. The guid can be replaced with something more meaningful like Unix Timestamp as well.
Create a custom file name every time and make use of File.WriteAllText (which will Creates a new file, write the contents to the file, and then closes the file. If the target file already exists, it is overwritten.) instead for File.AppendAllText
In your case the filePath should be dynamic which can be construct like this:
string basePath = ""; // this should be path to your directory in which you wanted to create the output files
string extension = ".xml";
string fileName = String.Format("{0}{1}{2}","MyFile",DateTime.Now.ToString("ddMMyy_hhmmss"),extension );
string filePath = Path.Combine(basePath,fileName);
In the above snippet the DateTime.Now.ToString("ddMMyy_hhmmss") will be the current time(at the time of execution of the code) which will be differ in each execution so the file name will differ in each run. And at some later points you can search/group files based on these common pattern.
One more thing:
In your code you have used a variable List<string> ls which is populated with all logs, and you are writing the the contents of log to the file, which contains only the last record. So the statement for writing the content should be:
File.WriteAllText(filePath, String.Join("\n",log));
or even simply
File.WriteAllLines(filePath, log);
simply make your filePath unique, for example by using Ticks
var filePath = $"app-log-{DateTime.Now.Ticks:X}.log";

FileUpload if exist concat (counter) to the name [duplicate]

This question already has answers here:
FileUpload - if file name exist concat a number between parentheses at the end of name
(3 answers)
Closed 5 years ago.
I have a fileupload control, What I want to achieve is to concat a nuber to it, in order it to be unique.
All the posts that I found are talking about adding a GUID or DateTime
What i want to achieve is if the file exist in folder then the file name will be filename + (counter)
Example:
The folder contain a file name- file.png
1) When I upload the same file name again, the existing one wont get delete and the new one will be called file(1).png.
2) When I upload the same file name again, (file.png)
now the new file will be called file(2)
I have this code which handle the 1'st case but not the second:
public static string GetUniqueName(string fileName)
{
string dir = Globals.Directories.GetCustomCategoryThumbnailDir();
string fileExtension = Path.GetExtension(fileName);
string fileNameWE = Path.GetFileNameWithoutExtension(fileName);
string[] files = Directory.GetFiles(dir, "*" + fileExtension)
.Select(Path.GetFileName)
.ToArray();
string uniqueName = fileNameWE;
int nextNum = 0;
bool fileExist = false;
string pattern = #"(.*)\(([\d]+)\)";
foreach (var file in files)
{
var tempFileName = Path.GetFileNameWithoutExtension(file);
var match = Regex.Match(tempFileName, pattern);
if (tempFileName.Equals(fileNameWE))
{
// file exist in folder
fileExist = true;
}
if (tempFileName.StartsWith(fileNameWE) && match.Success)
{
// there is a file name that start with "fileToUpload" name, we want to to take the number
nextNum = Convert.ToInt32(match.Groups[2].Value);
nextNum++;
}
}
if (nextNum == 0 && !fileExist)
{
// filename dont exist
return fileNameWE + fileExtension;
}
if (nextNum == 0 && fileExist)
{
// the file name exist without (1)
fileNameWE = $"{fileNameWE}(1)";
return fileNameWE + fileExtension;
}
else
{
var haveParentessis = Regex.Match(fileNameWE, pattern);
if (haveParentessis.Success)
{
// we need to reset the nextNum
nextNum = 1;
}
// return the new unique name with suffix
fileNameWE = string.Format("{0}({1})", fileNameWE, nextNum);
return fileNameWE + fileExtension;
}
}
How can I achieve that?
Yeah, that's cause your while loop as pointed below is local to the function and thus the counter variable which is also a local variable won't be maintained it's current value. So in essence every request you get a new page instance and thus your counter will get re-initialized to 0
while (File.Exists(Path.Combine(dir, fileNameWE + fileExtension)))
{
fileNameWE = fileNameWE + "(" + counter.ToString() + ")";
counter++;
}
To get this done, you should store the counter variable in Session and retrieve it back. Don't forget it's an web application and thus the state won't be maintained unless you do it explicitly
if (File.Exists(Path.Combine(dir, fileNameWE + fileExtension)))
{
counter = (Session["counter"] != null) ? ((int)Session["counter"])++ : default(int);
fileNameWE = fileNameWE + "(" + counter.ToString() + ")";
Session["counter"] = counter;
}
I got this to work by using regular expressions, below. No persistent counter is required. I think the concat problem is because there's nothing done to deal with the existing (1) suffix. I coded this potential solution and hope it helps! NB: only lightly tested in debugger, and I am a novice
{
string fileName = #"C:\Uploads\Testfile.bin";
string fileExtension = Path.GetExtension(fileName);
string fileNameWE = Path.GetFileNameWithoutExtension(fileName);
string pattern = #"(.*)\(([\d]+)\)$";
var match = Regex.Match(fileNameWE, pattern);
if (match.Success)
{
int nextNum = Convert.ToInt32(match.Groups[2].Value);
nextNum++;
fileNameWE = $"{match.Groups[1].Value}({nextNum})";
}
else
{
fileNameWE = $"{fileNameWE}(1)";
}
}

How to close a file handle byte[] firstHash = MD5.Create().ComputeHash(f1.OpenRead());

I have a piece of code which works nicely. However I need to close the file so I can perform file.move() function, this doesn't work because the file is used by another process. I need to use the correct file handle - can you guide me in the right direction?
static void DSCheckForDuplicates(string incomingfolder, string incomingarchivefolder, string quarantinefolder)
{
string[] F1 = Directory.GetFiles(incomingfolder);
string fname = "";
long FileOne;
long FileTwo;
bool FilesAreTrullyIdentical;
string FileStatusValue = "";
string Result = "";
string NewLocation = "";
foreach (string fileName in F1)
{
// FILE EXCLUSION LIST FROM DUPLICATE FILE CHECKS
if (fileName.Contains("xxx.DAT") || fileName.Contains("xxx.txt") || fileName.Contains("OrderHead.txt") )
{
Console.WriteLine("\nKnown file type..");
}
else
{
fname = Path.GetFileName(fileName);
FilesAreTrullyIdentical = false;
Console.WriteLine("Files present : The file is {0}...Press any key\n", fileName);
//Console.ReadKey();
if (File.Exists(incomingarchivefolder + #"\" + fname))
{
DuplicateFlag = true;
FileStatusValue = "DuplicateFilename";
DuplicateFileCounter++;
Narative += string.Format("\n________________________________________________________________________________________________________________\nFile Exception :{0}\n####################\n", DuplicateFileCounter );
Narative += string.Format ("Same filename exists in the two compared directories, Checking potential duplicate file contents in :{0}................\n", fileName);
FileInfo f1 = new FileInfo(fileName);
FileOne = f1.Length;
FileInfo f2 = new FileInfo(incomingarchivefolder + #"\" + fname);
FileTwo = f2.Length;
//if (FileOne == FileTwo)
//{
byte[] firstHash = MD5.Create().ComputeHash(f1.OpenRead());
byte[] secondHash = MD5.Create().ComputeHash(f2.OpenRead());
for (int i = 0; i < firstHash.Length; i++)
{
FilesAreTrullyIdentical = true;
if (firstHash[i] != secondHash[i])
FilesAreTrullyIdentical = false;
}
if (FilesAreTrullyIdentical == true)
{
FileStatusValue = "DuplicationFileNameDuplicateContents";
Console.WriteLine("Processed : WARNING!!! identical FILES contents FOUND {0}\n and {1}\n..............\n", fileName, incomingarchivefolder + #"\" + fname);
Narative += string.Format("\tProcessed : Please delete from incoming, WARNING!!! identical FILES contents\n\nPLEASE DELETE FILE:\t{0}..............\n", fileName);
Result = Path.GetFileName(fileName);
NewLocation += quarantinefolder + "\\" + Result;
Console.WriteLine("\n\n {0} ->\nMoving to {1} , press any key", fileName, NewLocation);
Console.ReadKey();
//File.Move(fileName, NewLocation); // THIS DOESNT WORK
You could capture the stream from f1.OpenRead() into a variable & pass that calling Close() when your done, instead however you should put the stream and MD5 reference within a using construct as currently you leave them undisposed. (This will also close the stream for you)
byte[] firstHash;
using (var stream = f1.OpenRead())
using (var md5 = MD5.Create())
{
firstHash = md5.ComputeHash(stream);
}

replacing text in a text file with \r\n

Currently I am building an agenda with extra options.
for testing purposes I store the data in a simple .txt file
(after that it will be connected to the agenda of a virtual assistant.)
To change or delete text from this .txt file I have a problem.
Although the part of the content that needs to be replaced and the search string are exactly the same it doesn't replace the text in content.
code:
Change method
public override void Change(List<object> oldData, List<object> newData)
{
int index = -1;
for (int i = 0; i < agenda.Count; i++)
{
if(agenda[i].GetType() == "Task")
{
Task t = (Task)agenda[i];
if(t.remarks == oldData[0].ToString() && t.datetime == (DateTime)oldData[1] && t.reminders == oldData[2])
{
index = i;
break;
}
}
}
string search = "Task\r\nTo do: " + oldData[0].ToString() + "\r\nDateTime: " + (DateTime)oldData[1] + "\r\n";
reminders = (Dictionary<DateTime, bool>) oldData[2];
if(reminders.Count != 0)
{
search += "Reminders\r\n";
foreach (KeyValuePair<DateTime, bool> rem in reminders)
{
if (rem.Value)
search += "speak " + rem.Key + "\r\n";
else
search += rem.Key + "\r\n";
}
}
// get new data
string newRemarks = (string)newData[0];
DateTime newDateTime = (DateTime)newData[1];
Dictionary<DateTime, bool> newReminders = (Dictionary<DateTime, bool>)newData[2];
string replace = "Task\r\nTo do: " + newRemarks + "\r\nDateTime: " + newDateTime + "\r\n";
if(newReminders.Count != 0)
{
replace += "Reminders\r\n";
foreach (KeyValuePair<DateTime, bool> rem in newReminders)
{
if (rem.Value)
replace += "speak " + rem.Key + "\r\n";
else
replace += rem.Key + "\r\n";
}
}
Replace(search, replace);
if (index != -1)
{
remarks = newRemarks;
datetime = newDateTime;
reminders = newReminders;
agenda[index] = this;
}
}
replace method
private void Replace(string search, string replace)
{
StreamReader reader = new StreamReader(path);
string content = reader.ReadToEnd();
reader.Close();
content = Regex.Replace(content, search, replace);
content.Trim();
StreamWriter writer = new StreamWriter(path);
writer.Write(content);
writer.Close();
}
When running in debug I get the correct info:
content "-- agenda --\r\n\r\nTask\r\nTo do: test\r\nDateTime: 16-4-2012 15:00:00\r\nReminders:\r\nspeak 16-4-2012 13:00:00\r\n16-4-2012 13:30:00\r\n\r\nTask\r\nTo do: testing\r\nDateTime: 16-4-2012 9:00:00\r\nReminders:\r\nspeak 16-4-2012 8:00:00\r\n\r\nTask\r\nTo do: aaargh\r\nDateTime: 18-4-2012 12:00:00\r\nReminders:\r\n18-4-2012 11:00:00\r\n" string
search "Task\r\nTo do: aaargh\r\nDateTime: 18-4-2012 12:00:00\r\nReminders\r\n18-4-2012 11:00:00\r\n" string
replace "Task\r\nTo do: aaargh\r\nDateTime: 18-4-2012 13:00:00\r\nReminders\r\n18-4-2012 11:00:00\r\n" string
But it doesn't change the text. How do I make sure that the Regex.Replace finds the right piece of content?
PS. I did check several topics on this, but none of the solutions mentioned there work for me.
You missed a : right after Reminders. Just check it again :)
You could try using a StringBuilder to build up you want to write out to the file.
Just knocked up a quick example in a console app but this appears to work for me and I think it might be what you are looking for.
StringBuilder sb = new StringBuilder();
sb.Append("Tasks\r\n");
sb.Append("\r\n");
sb.Append("\tTask 1 details");
Console.WriteLine(sb.ToString());
StreamWriter writer = new StreamWriter("Tasks.txt");
writer.Write(sb.ToString());
writer.Close();

c# service renaming files!

I have a windows service , that takes files with metadata(FIDEF) and corresponding video file and , translates the XML(FIDEF) using XSLT .
I get the file directory listing for FIDEF's and if a video file of the same name exists it translates it. That works ok , but it is on a timer to search every minute. I am trying to handle situations where the same file name enters the input directory but is already in the output directory. I just have it changing the output name to (copy) thus if another file enters i should get (copy)(copy).mov but the service won't start with filenames of the same directory already in the output , it works once and then does not seem to pick up any new files.
Any Help would be great as I have tried a few things with no good results. I believe its the renaming methods, but I've put most of the code up in case its a clean up issue or something else.
(forgive some of the names just trying different things).
private void getFileList()
{
//Get FILE LIST FROM Directory
try
{
// Process Each String/File In Directory
string result;
//string filename;
filepaths = null;
filepaths = Directory.GetFiles(path, Filetype);
foreach (string s in filepaths)
{
for (int i = 0; i < filepaths.Length; i++)
{
//Result Returns Video Name
result = Path.GetFileNameWithoutExtension(filepaths[i]);
FileInfo f = new FileInfo(filepaths[i]);
PreformTranslation(f, outputPath + result , result);
}
}
}
catch (Exception e)
{
EventLog.WriteEntry("Error " + e);
}
}
private void MoveVideoFiles(String Input, String Output)
{
File.Move(Input, Output);
}
private string GetUniqueName(string name)
{
//Original Filename
String ValidName = name;
//remove FIDEF from filename
String Justname1 = Path.GetFileNameWithoutExtension(name);
//get .mov extension
String Extension2 = Path.GetExtension(Justname1);
//get filename with NO extensions
String Justname = Path.GetFileNameWithoutExtension(Justname1);
//get .Fidef
String Extension = Path.GetExtension(name);
int cnt = 0;
//string[] FileName = Justname.Split('(');
//string Name = FileName[0];
while (File.Exists(ValidName)==true)
{
ValidName = outputPath + Justname + "(Copy)" + Extension2 + Extension;
cnt++;
}
return ValidName;
}
private string getMovFile(string name)
{
String ValidName = name;
String Ext = Path.GetExtension(name);
String JustName = Path.GetFileNameWithoutExtension(name);
while(File.Exists(ValidName))
{
ValidName = outputPath + JustName + "(Copy)" + Ext;
}
return ValidName;
}
//Preforms the translation requires XSL & FIDEF name.
private void PreformTranslation(FileInfo FileName, String OutputFileName , String result)
{
string FidefName = OutputFileName + ".FIDEF";
String CopyName;
String copyVidName = outputPath + result;
XslCompiledTransform myXslTransform;
myXslTransform = new XslCompiledTransform();
try
{
myXslTransform.Load(XSLname);
}
catch
{
EventLog.WriteEntry("Error in loading XSL");
}
try
{ //only process FIDEF's with corresponding Video file
if (AllFidef == "no")
{
//Check if video exists if yes,
if (File.Exists(path + result))
{
//Check for FIDEF File Already Existing in the Output Directory.
if (File.Exists(FidefName))
{
//Get unique name
CopyName = GetUniqueName(FidefName);
copyVidName= getMovFile(copyVidName);
//Translate and create new FIDEF.
//double checking the file is here
if (File.Exists(outputPath + result))
{
myXslTransform.Transform(FileName.ToString(), CopyName);
File.Delete(FileName.ToString());
MoveVideoFiles(path + result, copyVidName);
}
////Move Video file with Corresponding Name.
}
else
{ //If no duplicate file exsists in Directory just move.
myXslTransform.Transform(FileName.ToString(), OutputFileName + ".FIDEF");
MoveVideoFiles(path + result, outputPath + result);
}
}
}
else
{
//Must have FIDEF extension
//Processes All FIDEFS and moves any video files if found.
myXslTransform.Transform(FileName.ToString(), OutputFileName + ".FIDEF");
if (File.Exists(path + result))
{
MoveVideoFiles(path + result, outputPath + result);
}
}
}
catch (Exception e)
{
EventLog.WriteEntry("Error Transforming " + "FILENAME = " + FileName.ToString()
+ " OUTPUT_FILENAME = " + OutputFileName + "\r\n" +"\r\n"+ e);
}
}
There is a lot wrong with your code. getFileList has the unneeded inner for loop for starters. Get rid of it. Your foreach loop has s, which can replace filepaths[i] from your for loop. Also, don't do outputPath + result to make file paths. Use Path.Combine(outputPath, result) instead, since Path.Combine handles directory characters for you. Also, you need to come up with a better name for getFileList, since that is not what the method does at all. Do not make your method names liars.
I would simply get rid of MoveVideoFiles. The compiler just might too.
GetUniqueName only works if your file name is of the form name.mov.fidef, which I'm assuming it is. You really need better variable names though, otherwise it will be a maintenance nightware later on. I would get rid of the == true in the while loop condition, but that is optional. The assignment inside the while is why your files get overwritten. You always generate the same name (something(Copy).mov.fidef), and as far as I can see, if the file exists, I think you blow the stack looping forever. You need to fix that loop to generate a new name (and don't forget Path.Combine). Maybe something like this (note this is untested):
int copyCount = 0;
while (File.Exists(ValidName))
{
const string CopyName = "(Copy)";
string copyString = copyCount == 0 ? CopyName : (CopyName + "(" + copyCount + ")");
string tempName = Justname + copyString + Extension2 + Extension;
ValidName = Path.Combine(outputPath, tempName);
copyCount++;
}
This generates something(Copy).mov.fidef for the first copy, something(Copy)(2).mov.fidef for the second, and so on. Maybe not what you want, but you can make adjustments.
At this point you have a lot to do. getMovFile looks as though it could use work in the same manner as GetUniqueName. You'll figure it out. Good luck.

Categories