C# mass File renamer - c#

i want to create C# mass file renamer, here is my UI
i have created tes folder, inside of tes there's a file which is 1.txt.
i want to create my program to add prefix and suffix to the files, so 1.txt will become
prefix1suffix
but then i got an error
it's said file already exist though there's only one file on tes folder, which is 1.txt how do i make it work ? where's the error comes from ?
i have tried the following code
private void Rename(string prefix, string filepath, string suffix)
{
//i don't use prefix suffix yet to make sure if my function works
DirectoryInfo d = new DirectoryInfo(filepath);
FileInfo[] file = d.GetFiles();
try
{
foreach (FileInfo f in file )
{
File.Move(f.FullName,"stackoverflow");
}
}
catch (Exception e)
{
cmd.cetakGagal(e.ToString(), title);
}
cmd.cetakSukses("Rename Success", title);
}
and it returns same error as the second picture above.
the following picture is tes folder, there's nothing in tes folder except 1.txt

You are calling File.Move() with a full path for your sourceFileName and a relative path for your destFileName. The relative file path is relative to the current working directory and not to the source file path. I expect that a stackoverflow file exists in the current working directory, most likely created the first time you ran this code.

your File.Move is changing them all to StackOverflow not using the prefix and suffix. If you only have one file in the directory it shouldn't be an issue. Are you sure there is only 1 file?
public static void Move(
string sourceFileName,
string destFileName
)
Looking at this answer might be the clue as you are specifying relative path for the destination file. To obtain the current working directory, see GetCurrentDirectory
The sourceFileName and destFileName arguments are permitted to specify
relative or absolute path information. Relative path information is
interpreted as relative to the current working directory.
You should change
File.Move(f.FullName,"stackoverflow");
to
string fileName = f.Name.Replace(f.Extenstion,string.Empty);
string newFileName = string.Format("{0}{1}{2}",prefix,fileName,suffix);
string newFileWithPath = Path.Combine(f.Directory,newFileName);
if (!File.Exists(newFileWithPath))
{
File.Move(f.FullName,newFileWithPath);
}

The code above will give you that error since, after the first run through, "stackoverflow" exists as a file. Make sure that you check if the destination file exists (using File.Exists) before calling File.Move.

Since your goal is renaming, I would suggest using a test folder filled with files rather than using a piecemeal approach. See if something like this helps:
private void Rename(string prefix, string filepath, string suffix)
{
//i don't use prefix suffix yet to make sure if my function works
DirectoryInfo d = new DirectoryInfo(filepath);
FileInfo[] file = d.GetFiles();
try
{
foreach (FileInfo f in file )
{
f.MoveTo(#filepath + #"\" + prefix + f.Name.Insert(f.Name.LastIndexOf('.'),suffix));
}
}
catch (Exception e)
{
cmd.cetakGagal(e.ToString(), title);
}
cmd.cetakSukses("Rename Success", title);
}
on a side note using a listview to display the filenames and the changes before they're committed will help prevent unwanted changes.

Related

How to search for a file extension (.xls) and change it's name? C#

The product I'm using is a Beijer HMI, currently i can generate a report and save it to a known location (my desktop - C:\Users\mrdav\Desktop).
I need to be able to search on my desktop for a file extension .xls and change its name.
When the report is generated by the HMI, it uses the date and time which means when the file is generated the name will be different every time.
On the press of a button i need to search my desktop for the .xls file and change its name to a variable.
// This is my variable with my program
string NewName = Globals.Tags.Tag1.Value;
The code that is generated needs to sit within the below example.
public partial class Screen1
{
void Button1_Click(System.Object sender, System.EventArgs e)
{
// Code to be added here...
}
}
Hopefully someone can help, I’m using windows compact framework so limited on functionality.
Any questions please let me know.
Thanks in advance,
Dave
Here is an example how you can do that:
DirectoryInfo dir = new DirectoryInfo(sExportPath);
FileInfo[] Files = dir.GetFiles("*.csv");
foreach(FileInfo file in Files )
{
// rename file
System.IO.File.Move(file.FullName, GenerateNewFileName());
}
//elsewhere in the class
private string GenerateNewFileName()
{
//here is where you implement creating or getting the filename that you want your file to be renamed to. An example might look like the below
string serialNumber = GetSerialNumber(); //Get the serial number that you talked about in the question. I've made it a string, but it could be an int (it should be a string)
return Path.ChangeExtension(serialNumber,".xls"); //to use path you will need a using statement at the top of your class file 'using System.IO'
}
This seems to work...but i know its not as tidy as it could be.
Any suggestions?
Thanks to all that helped, got there in the end!
void Button_Click(System.Object sender, System.EventArgs e)
{
try
{
// Location for new file
string NewFileName = #"c:\users\mrdav\desktop\testfolder\";
// Add varibale name to new file
NewFileName += Globals.Tags.Tag1.Value;
// add .xls extention to new file
NewFileName += ".xls";
//show new file name to check all ok
MessageBox.Show (NewFileName);
//search for .xls in known directory
DirectoryInfo di = new DirectoryInfo(#"c:\users\mrdav\desktop");
FileInfo[] Files = di.GetFiles("*.xls");
// if files exist with .xls extention
foreach(FileInfo file in Files )
{
// show full file name
MessageBox.Show (file.FullName);
//rename old file to new file name and move to new folder
File.Move(file.FullName, NewFileName);
}
}
catch (Exception ex)
{
MessageBox.Show (ex.ToString());
}
}

IOException file already exists C#

private void btn_Backup_Click(object sender, EventArgs e)
{
List<DirectoryInfo> SourceDir = this.lbox_Sources.Items.Cast<DirectoryInfo>().ToList();
string TargetDir = this.tbox_Target.Text;
foreach (DirectoryInfo directory in SourceDir)
{
foreach (var file in directory.GetFiles())
if (this.checkbox_zipfiles.Checked == true)
{
System.IO.Compression.ZipFile.CreateFromDirectory(directory.FullName, TargetDir + #"\test.zip");
}
else
{
Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory(directory.FullName, TargetDir, true);
}
}
}
I'm creating a backup application and when I try to zip the files I need to backup it says: "The file 'C:\Users\Lada1208\Desktop\test\test.zip' already exists."
even thought the folder is empty before so it's trying to create the test.zip file two times for some reason. Any idea why?
As pointed out by s.m. in the comment above, the call to ZipFile.CreateFromDirectory() will attempt to create a zip file with the same location and file name for all the source directories.
If the intention is to create a single archive containing files from all the source directories, then the Zipfile.CreateFromDirectory() "shortcut" method cannot be used. Instead, you need to call ZipFile.Open(), get a ZipArchive object and use its CreateEntry() method to add every file individually.

File.Copy error - C# - IOException The filename, directory name, or volume label

Trying to copy all files/directories inside a directory to a new location that I create.
Users select the 'backup drive' to work with to in a combobox, then when they click the backup desktop button it simply creates a backup directory on that drive and copies all the files into that directory.
The backup directory gets created on the drive appropriately - but the first file it hits it kicks off an error.
private void backupDesktopButton_Click(object sender, EventArgs e)
{
//set the destionationLocation to the selectedDrive
string selectedDrive = backupDriveCombo.SelectedItem.ToString();
string destinationLocation = selectedDrive+"Backups-" + DateTime.Now.Month.ToString()+"-"+DateTime.Now.Year.ToString()+"\\Desktop\\";
if (!Directory.Exists(destinationLocation))
{
Directory.CreateDirectory(destinationLocation);
}
string desktopFolder = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
string[] fileList = Directory.GetFiles(desktopFolder);
foreach (string file in fileList)
{
//move the file
File.Copy(file, destinationLocation);
}
}
I get the error:
IOException was unhandled.
The filename, directory name, or volume label syntax is incorrect.
In the 'Autos' window (VS2010) I see the locations are set correctly:
destinationLocation = the appropriate directory (C:\Backups-8-2016\Desktop\)
file = the appropriate first file (C:\Users\myusername\Desktop\myshortcut.url)
What am I missing? I have all rights to be able to copy/paste/create things and the directory to store it gets created - just a problem moving the file.
From the documentation https://msdn.microsoft.com/en-us/library/c6cfw35a(v=vs.110).aspx
the second parameter:
The name of the destination file. This cannot be a directory or an existing file.
you need to concat the filename to the folder.
Try something like this
string[] fileList = Directory.GetFiles(desktopFolder);
foreach (string file in fileList)
{
string targetFile = Path.Combine(destinationLocation, Path.GetFileName(file));
if (File.Exists(targetFile)) File.Delete(targetFile);
File.Copy(file, targetFile);
}

C# PDF reader only works with the pdf files in the debug folder

I have an issue with an C# application. I am trying to read some PDF files and load the data into a database.
The application make works good only when the PDF files are in a specific folder. the folder is the debug folder of the project.
I need to load the PDF files from any folder.
public string LecturaPDF(string nombreArchivo)
{
PdfReader lectorPDF = new PdfReader(nombreArchivo);
string TextoPuro = string.Empty;
string[] TextoDividido;
string TextoFinal = string.Empty;
for (int a = 1; a <= lectorPDF.NumberOfPages; a++)
{
ITextExtractionStrategy pdfParser =
new iTextSharp.text.pdf.parser.SimpleTextExtractionStrategy();
TextoPuro = TextoPuro + PdfTextExtractor.GetTextFromPage(lectorPDF, a, pdfParser);
}
lectorPDF.Close();
TextoDividido = TextoPuro.Split('\n');
for (int b = 0; b < TextoDividido.Count(); b++)
{
if (TextoDividido[b].First()== '7')
{
TextoFinal = TextoFinal + TextoDividido[b] + ";";
}
}
return ';' + TextoFinal;
}
the error occur in this line PdfReader lectorPDF = new PdfReader(nombreArchivo);
the error say:
C:\user\me\MyDocuments\Projects\Project1\bin\debug\test.pdf not found
as file or resource
With this function I open a dialog box to select the file and call the function to read the pdf file:
private void cmdProcesar_Click(object sender, RoutedEventArgs e)
{
if (dialogoArchivo.ShowDialog().Value)
{
for (int a = 0; a < dialogoArchivo.FileNames.Count(); a++)
{
lblEstado.Dispatcher.Invoke(DispatcherPriority.Background, (Action)(() => lblEstado.Content =
"Procesando archivos contra Billing..."));
archivo.InsercionArchivo(dialogoArchivo.SafeFileNames[a], G_Fecha,
archivo.LecturaPDF(System.IO.Path.GetFullPath(dialogoArchivo.SafeFileNames[a])),
Convert.ToDouble(txtTarifa.Text),
conexion.ConexionOracle);
}
}
This is my first time with C# and I don't know why only works wwhen I read the files from the project debug folder
Any advice will appreciated
Thanks in advance
UPDATE
private void cmdProcesar_Automatico(object sender, RoutedEventArgs e)
{
string carpeta = "C:\\temp";
DirectoryInfo dir = new DirectoryInfo(carpeta);
FileInfo[] documentos = dir.GetFiles("*.pdf");
txtTarifa.Text = "1.48";
foreach (FileInfo archivopdf in documentos)
{
lblEstado.Dispatcher.Invoke(DispatcherPriority.Background, (Action)(() => lblEstado.Content =
"Procesando archivos contra Billing..."));
archivo.InsercionArchivo(archivopdf.Name, G_Fecha,
archivo.LecturaPDF(System.IO.Path.GetFullPath(archivopdf.Name)),
Convert.ToDouble(txtTarifa.Text),
conexion.ConexionOracle);
}
}
I change the function to automatically read all the file in a specific folder and process every file.
But I get the same error:
C:\user\me\MyDocuments\Projects\Project1\bin\debug\test.pdf not found
as file or resource
From the documentation of OpenFileDialog.SafeFileNames (emphasis mine):
Gets an array of file names and extensions for all the selected files in the dialog box. The file names do not include the path.
As it doesn't contain the path, the current path will be used which when you're running in the debugger will be bin\debug by default.
If you know the directory that the file should be chosen from you could add it to the file name (using Path.Combine) but if you would prefer the full path you can use the FileNames property which according to the documentation (again, emphasis mine):
Each file name includes both the file path and the extension. If no files are selected, this method returns an empty array.
In your context you'd need to change this line:
archivo.LecturaPDF(System.IO.Path.GetFullPath(dialogoArchivo.SafeFileNames[a])),
to
archivo.LecturaPDF(System.IO.Path.GetFullPath(dialogoArchivo.FileNames[a])),
EDIT
To answer the question in your edit - you are getting FileInfo objects for all pdf files in C:\temp but you are then using System.IO.Path.GetFullPath(archivopdf.Name) to get the file path to pass to archivo.LecturaPDF. The documentation for Path.GetFullPath states (emphasis mine again):
This method uses current directory and current volume information to fully qualify path. If you specify a file name only in path, GetFullPath returns the fully qualified path of the current directory.
Imagine that you have a FileInfo for the file c:\temp\example.pdf. When you call System.IO.Path.GetFullPath(archivopdf.Name) on that FileInfo you are essentially calling System.IO.Path.GetFullPath("example.pdf"). This will give the file name of example.pdf but it will use the current path for the path which in your case is C:\user\me\MyDocuments\Projects\Project1\bin\debug\ (the path your executable is running from).
This results in a fully qualified file name of C:\user\me\MyDocuments\Projects\Project1\bin\debug\example.pdf which isn't what you want and presumably doesn't exist.
As you already have a FileInfo object the solution is straightforward - you can use the FullName property directly without the need to call GetFullPath. The FullName property will give you the correct fully qualified name of c:\temp\example.pdf.
Your code should therefore read:
archivo.InsercionArchivo(archivopdf.Name, G_Fecha,
archivo.LecturaPDF(archivopdf.FullName),
Convert.ToDouble(txtTarifa.Text),
conexion.ConexionOracle);

The directory name is invalid

Why am I getting this error? I am using the correct path.
Problem : You are providing the Path of File
Solution : You need to provide the path of Directory to get all the files in a given Directory based on your search pattern.
From MSDN: Directory.GetFiles()
Returns the names of files (including their paths) that match the
specified search pattern in the specified directory.
Try this:
string directoryName = Path.GetDirectoryName(e.FullPath);
foreach(String filename in Directory.GetFiles(directoryName,"*.eps"))
{
//your code here
}
You want the directory, not the filename.
At the moment, the value of e.FullPath is "C:\\DigitalAssets\\LP_10698.eps". It should be "C:\\DigitalAssets".
string[] fileNames = Directory.GetFiles(string path) requires a directory, you are giving it a directory + filename.
MSDN:
Returns the names of files (including their paths) that match the
specified search pattern in the specified directory.
foreach(string filename in Directory.GetFiles(e.FullPath, "*.eps"))
{
// For this to work, e.FullPath needs to be a directory, not a file.
}
You can use Path.GetDirectoryName():
foreach(string filename in Directory.GetFiles(Path.GetDirectoryName(e.FullPath), "*.eps"))
{
// Path.GetDirectoryName gets the path as you need
}
You could create a method:
public string GetFilesInSameFolderAs(string filename)
{
return Directory.GetFiles(Path.GetDirectoryName(filename), Path.GetExtension(filename));
}
foreach(string filename in GetFilesInSameFolderAs(e.FullPath))
{
// do something with files.
}
e.FullPath seems to be a file, not a directory. If you want to enumerate *.eps files, the first argument to GetFiles should be a directory path: #"C:\DigitalAssets"
the first argument of GetFiles should be only "C:\DigitalAssets"
e.FullPath include the file name in it.
Directory.GetFiles used to get file names from particular directory. You are trying to get files from file name which is not valid as it gives you error. Provide directory name to a function instead of file name.
You can try
Directory.GetFiles(System.IO.Path.GetDirectoryName(e.FullPath),"*.eps")
For deleting files from a directory
var files = Directory.GetFiles(directory)
foreach(var file in files)
{
File.Delete(file);
}
In short to delete the file use
File.Delete(filePath);
and to delete the directory
Directory.Delete(directoryPath)

Categories

Resources