If file exist in the folder and in the database, how can I add extension at the end of the filename?
For example, if a filename like this exists:
JOHN_DENVER_SMITH.pdf
the code should rename the 2nd record to JOHN_DENVER_SMITH_(1).pdf
.
Here's my code:
FileInfo fileInfo = new FileInfo(oldPath);
if (fileInfo.Exists)
{
try
{
if (!Directory.Exists(newPath))
{
Directory.CreateDirectory(newPath);
}
fileInfo.MoveTo(string.Format("{0}{1}{2}", newPath, firstname.Text "_" midlename.Text "_" lastname.Text, fileInfo.Extension));
dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);
}
}
CodePudding user response:
Validate if the file already exists on the new location. If it does, add a counter value at the end of your file name and try again. Repeat until the filename doesn't exist.
FileInfo fileInfo = new FileInfo(oldPath);
if (fileInfo.Exists)
{
try
{
if (!Directory.Exists(newPath))
{
Directory.CreateDirectory(newPath);
}
var newFileName = string.Format("{0}{1}{2}", newPath, firstname.Text "_" midlename.Text "_" lastname.Text, fileInfo.Extension);
var i = 0;
while (File.Exists(newFileName))
{
newFileName = string.Format("{0}{1}_({2}){3}", newPath, firstname.Text "_" midlename.Text "_" lastname.Text, i, fileInfo.Extension);
}
fileInfo.MoveTo(newFileName);
dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);
}
}
CodePudding user response:
Try this:
static string GetFilePath(string path)
{
// do nothing if file not exists
if(!File.Exists(path)) return path;
int index = path.LastIndexOf(".");
var ext = index == -1 ? String.Empty : path.SubString(index);
var pathNoExt = index == -1 ? path : path.SubString(0, index);
int i = 0;
string result = null;
// Loop until the file does not exist
while(File.Exists(result = $"{pathNoExt}({ i}){ext}"));
return path;
}
Usage:
fileInfo.MoveTo(GetFilePath($"{newPath}{firstname.Text}_{midlename.Text}_{lastname.Text}{fileInfo.Extension}"));
You can replace string
with ReadOnlySpan<char>
and SubString
with Slice
for better performance.
CodePudding user response:
You can write a code to generate the new path like this.
private string NewPathFor(string oldPath)
{
var fileInfo = new FileInfo(oldPath);
var newPath = oldPath;
for (var i = 0; !fileInfo.Exists; i )
{
newPath = $"{Path.GetFileNameWithoutExtension(fileInfo.Name)}_({i}).{fileInfo.Extension}";
fileInfo = new FileInfo(newPath);
}
return newPath;
}
And then call it,
var oldPath=$"{firstname.Text}_{midlename.Text}_{lastname.Text}.pdf";
fileInfo.MoveTo(NewPathFor(oldPath));
dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);
CodePudding user response:
If Not (IO.File.Exists(fileName & "(" & fileNumber.ToString & ")" & fileExtension) Then 'The file does not exist, do something.. Exit Do Else 'The file does exist, so increment and try the next one...