1
I am trying to develop a small program to rename lots of files (pdf, etc). Imagine that the default is "1250_F1_001A_E01-001A00.pdf" and at the end would get "1250_F1001A00.pdf", kept the first 7 and the last 6 of any file. The one in the middle would be eliminated.
The problem is in fileName.LastIndexOf(3, 3));
constantly gives error.
The code I’m trying to produce is as follows::
namespace RenomeiaPdfs
{
class Program
{
static void Main(string[] args)
{
const string DIRECTORY_PATH = @"C:\Users\...\RENOMEIA";
if (Directory.Exists(DIRECTORY_PATH))
{
string[] filePathList = Directory.GetFiles(DIRECTORY_PATH);
foreach (string filePath in filePathList)
{
if (File.Exists(filePath))
{
// Get the file name
string fileName = Path.GetFileName(filePath);
// Get the file extension
string fileExtension = Path.GetExtension(filePath);
// Get the file name without the midle part
string fileTitle = fileName.Substring(0, fileName.LastIndexOf(3, 3));
File.Move(filePath, DIRECTORY_PATH + @"\" + fileTitle + fileExtension);
}
}
}
}
}
}
Thank you Joabe Alexandre. There are never repeated filenames. The name patterns are always these: 2000_F1_001_008G_E01-006G00.pdf / 2000_F1_001_008G_E01-007G00.pdf, etc and should give rise to the names: 2000_F1006G00.pdf/ 2000_F1007G00.pdf
– Paulo Ferreira
I changed the code snippet to get the name without the extension (var filename = Path.Getfilenamewithoutextension(item.Path)), since with the extension it gave me a repeat error. You’ve tested that too?
– Joabe Alexandre
The problem is in string fileTitle = $"{filename.Substring(0, 27)}{filename.Substring(filename.Length - 8, 10)}"; If you do not remove the correct characters, then you can create files with the same name.
– Paulo Ferreira
In this excerpt, the first subtring is getting the name of the complete file (in the question the 7 first digits are asked) and at the end is getting a string beyond the size of the text. It is not clear what you are seeking.
– Joabe Alexandre
string fileTitle = $"{filename.Substring(0, 7)}{filename.Substring(filename.Length - 6, 7)}"; The problem is here. It does not remove the correct characters.
– Paulo Ferreira