Renaming all files in folder in numeric order - c#

i know this seems pretty simple and i know theres other questions asking this but i just need to know what im personally doing wrong and why it doesnt work because it should.
int ImageCounter = 1;
foreach (var Image in ImageFilePaths)
{
{
// Console.WriteLine(Image);
// Console.WriteLine(RenameFolderPath + #"\" + ImageCounter + ".jpeg");
File.Move(Image, RenameFolderPath + #"\" + ImageCounter + ".jpeg");
ImageCounter++;
}
}
So theres about 150 images in a folder and after running this, im left with 11, 10 of which are numbered 1-10 and the 11th is left with its original name.
if i print (image) it will print about 150 of the original names, if i print the 2nd writeline, it will print the exact same but "1 - about 150" instead of the original name. so theres no problems there, it must be with the file.move but i cannot see anything wrong

Not sure what the rest of your code looks like, but this works for me:
void Main()
{
MoveFiles(#"c:\Temp\MoveTest", #"C:\Temp\MoveTest1");
}
public void MoveFiles(string fromDir, string toDir)
{
int ImageCounter = 1;
// Take a snapshot of the file system.
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(fromDir);
IEnumerable<System.IO.FileInfo> ImageFilePaths = dir.GetFiles("*.*", System.IO.SearchOption.TopDirectoryOnly);
foreach (var Image in ImageFilePaths)
{
{
Console.WriteLine(Image);
Console.WriteLine(toDir + #"\" + ImageCounter + ".jpeg");
File.Move(Image.FullName, toDir + #"\" + ImageCounter + ".jpeg");
ImageCounter++;
}
}
}

Related

How to rename images in a folder after an image is deleted from them?

I have 5 images in a folder. The name of the images are:
img1.jpg
img2.jpg
img3.jpg
img4.jpg
img5.jpg
If I delete img3, I want the other images below 3 to move up and be renamed like:
img1.jpg
img2.jpg
img3.jpg
img4.jpg
I can delete specific image from the folder like this:
int i = 3;
string imgpath = #"C:\images" + "/" + "img" + i.ToString() + ".jpg";
File.Delete(imgpath );
But how do I rename the images below img3 ?
As suggested by David, I used a loop as below to fix the issue:
int filecount = Directory.GetFiles(path, "*", SearchOption.TopDirectoryOnly).Length;
int position = 3
for (int i = position; i < filecount ; i++)
{
string filename1= #"C:\images" + "/" + "img" + (i + 1).ToString() + ".jpg";
string filename2= #"C:\images" + "/" + "img" + (i).ToString() + ".jpg";
File.Move(filename1, filename2);
}

Copy picture to folder and rename the copy with numbers from 1, sequentially

Here is all I want to do: Every time the button is clicked, an openfile dialog is opened, the user clicks on a picture, then this picture is copied to a specific folder and renamed to a number. Every picture's name in this folder should be a number, but they must all be different. My code so far:
if (openfile.ShowDialog() == DialogResult.OK)
{
try
{
File = Image.FromFile(openfile.FileName);
pictureBox3.Image = File;
int i = 0;
if (System.IO.File.Exists(picturedir + "\\" + i.ToString() + ".png") == true)
{
i++;
MessageBox.Show(picturedir + "\\" + i.ToString() + ".png" + ".....Already Exists.");
}
else if (System.IO.File.Exists(picturedir + "\\" + i.ToString() + ".png") == false)
{
System.IO.File.Copy(openfile.FileName, picturedir + "\\" + i.ToString() + ".png", true);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Of course here, the first picture is copied and renamed to "0.png" but the next pictures are not copied at all, because the "if" gives true. Any ideas ? Thanks.
You could do this:
...
int i = 0;
while (System.IO.File.Exists(picturedir + "\\" + i.ToString() + ".png") == true)
{
i++;
// I wouldn't show that message each time, gonna get pretty old for lots of pics!
}
System.IO.File.Copy(openfile.FileName, picturedir + "\\" + i.ToString() + ".png", true);
...
If you want the next number, you can enumerate the existing files, find the maximum number now in use and add 1. Something like:
var files = Directory.EnumerateFiles(myCurrentDirectory, "*.png");
var fileNumStrings = from file in files select Path.GetFileNameWithoutExtension(file);
var max = 0;
foreach (var fileNumString in fileNumStrings)
{
if (int.TryParse(fileNumString, out var filenum))
{
if (filenum > max)
{
max = filenum;
}
}
}
var nextNum = max + 1;

C# rename all files in a folder

I hve a small code which can rename all files (picture) in a folder and it looks like this:
static void Main(string[] args)
{
try
{
DirectoryInfo d = new DirectoryInfo(#"C:\Users\filip_000\Pictures\Prag");
int i = 1;
foreach (var file in d.GetFiles())
{
Directory.Move(file.FullName, #"C:\Users\filip_000\Pictures\Prag\" + "Prag_" + i.ToString() + ".jpg");
i++;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
It works fine, but I would like to rename the pictures (Prag_1, Prag_2, Prag_3...) according to date/time of the file. I mean: the first picture I made on 25.03.2016 16:04 should be "Prag_1" and the last picture I took on 27.03.2016 19:19 should be "Prag_n".
I hope I could explain my issue. Thank you for helping.
Filippo.
Order files on LastWriteTime and then move.
foreach (var file in d.GetFiles().OrderBy(f => f.LastWriteTime))
{
Directory.Move(file.FullName, #"C:\Users\filip_000\Pictures\Prag\" + "Prag_" + i.ToString() + ".jpg");
i++;
}
OrderBy CreationTime property can be good choice:
foreach (var file in d.GetFiles().OrderBy(f => f.CreationTime))
{
Directory.Move(file.FullName, #"E:\MP3 #1\Prag\" + "Prag_" + i.ToString() + ".jpg");
i++;
}

Port from winForms to Windows phone 8.0 C#

can someone help me out by porting/translating this piece of c# code wrote in winForms to Windows phone 8.0 ? Im really struggling with it and i cant make it work i probably read every single documentation that i could get my hands on but i just cant make it work. I know that stackover flow is not place where people write code for you but im hopeless.. any help is appreciated Im trying to load some info about my app from a text document and image im loading those things in array of images and array of strings. Here's the code :
private static string[] _folderPaths = Directory.GetDirectories(#"Folders");
private string[] _imagePaths;
private List<string> _questionsPaths = new List<string>();
private List<string> _correctAnswersPaths = new List<string>();
private List<string> _allAnswersPaths = new List<string>();
for (int i = 0; i < _folderPaths.Length; i++)
{
var _tempLocations = Directory.GetFiles(_folderPaths[i], (i + 1).ToString() + "*.txt*");
_imagePaths = Directory.GetFiles(_folderPaths[i], "*.png", SearchOption.TopDirectoryOnly);
foreach (string item in _tempLocations)
{
if (item == "Folders\\" + (i + 1).ToString() + "\\" + (i + 1).ToString() + ".txt")
{
_questionsPaths.Add(item);
}
if (item == "Folders\\" + (i + 1).ToString() + "\\" + (i + 1).ToString() + "answer" + ".txt")
{
_correctAnswersPaths.Add(item);
}
if (item == "Folders\\" + (i + 1).ToString() + "\\" + (i + 1).ToString() + "answers" + ".txt")
{
_allAnswersPaths.Add(item);
}
}
}
The corresponding types used in Windows Phones are (not precise mapping, of course):
Directory -> StorageFolder
Directory.GetDirectories -> StorageFolder.GetFoldersAsync
Directory.GetFiles -> StorageFolder.GetFilesAsync
So the translated code would be something like this (you need to be familiar with the new await-async keywords too)
using Windows.Storage;
var folder = await ApplicationData.Current.LocalFolder.GetFolderAsync("Folders");
var subFolders = await folder.GetFoldersAsync();
foreach (StorageFolder subFolder in subFolders)
{
var tempFiles = await subFolder.GetFilesAsync(...

File transfer error

I'm making an application, and at some point it does the following: Checks if a file that will be created, already exists in a directory (output), if it exists, he sends for the Errors folder, if not, it sends to the output folder. But comes a point where the program transfers the file to the folder errors, and buga, saying that the file does not exist, for example, he just transfer it t file (49) .png, and he again read the same file ! Funny is only in some cases it
if (System.IO.File.Exists(entrada + "t (" + i + ").png")){
string[] datas1 = Spire.Barcode.BarcodeScanner.Scan(#"C:\\QTRACK\\Entrada\\PNG\\t (" + i + ").png");
this.textBox1.Text = datas1[0];
foreach (string code in datas1)
{
DirectoryInfo exit = new DirectoryInfo(#"C:/QTRACK/Erro/");
FileInfo[] teste = exit.GetFiles("*.png");
x = teste.Length +1;
for (c = x; c <= 1000000000; c++)
{
if (System.IO.File.Exists(saida + code + ".png"))
{
System.IO.File.Move(entrada.ToString() + "t (" + i + ").png", erro + "e" + c + ".png");
}
else
{
System.IO.File.Move(entrada.ToString() + "t(" + i + ").png", saida + code + ".png");
}
}
}
}
else
{
}
}
}
It gives the error FileNotFoundExecption, however, was himself who changed the file and're trying to change again. Please help.

Categories

Resources