-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathFileManagerClass.cs
276 lines (242 loc) · 11.2 KB
/
FileManagerClass.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.Versioning;
using System.Windows.Forms;
[SupportedOSPlatform("windows")]
public class FileManager
{
// Method to get the number format based on the number of digits
private string GetNumberFormat(int numDigits) => new string('0', numDigits);
// Method to get an ordered dictionary of files based on the numeric part of the filename
private SortedDictionary<int, string> GetOrderedFiles(string[] filesList)
{
var orderedFilesDict = new SortedDictionary<int, string>();
foreach (string filePath in filesList)
{
string fileName = Path.GetFileNameWithoutExtension(filePath);
int underscoreIndex = fileName.LastIndexOf('_');
if (underscoreIndex != -1 && underscoreIndex < fileName.Length - 1)
{
string numberPart = fileName.Substring(underscoreIndex + 1);
if (int.TryParse(numberPart, out int numericValue))
{
orderedFilesDict[numericValue] = filePath;
}
}
}
return orderedFilesDict;
}
// Hold info about the padding update result from UpdateZeroPadding method
public class PaddingUpdateResult
{
public bool ChangesMade { get; set; }
public int FilesRenamed { get; set; }
public string NewFormat { get; set; }
public List<string> Errors { get; set; } = new List<string>();
}
// Method to update the zero padding of filenames to ensure consistency
public PaddingUpdateResult UpdateZeroPadding(string folderPath, string fileBaseNameToUse)
{
string searchPattern = $"{fileBaseNameToUse}_*.png";
string[] files = Directory.GetFiles(folderPath, searchPattern);
if (files.Length == 0) return new PaddingUpdateResult { NewFormat = "No files found." };
int digitCount = (int)Math.Floor(Math.Log10(files.Length)) + 1;
string newFormat = $"D{digitCount}";
PaddingUpdateResult result = new PaddingUpdateResult { NewFormat = newFormat };
foreach (string file in files)
{
string baseName = Path.GetFileNameWithoutExtension(file);
int underscoreIndex = baseName.LastIndexOf('_');
if (underscoreIndex != -1 && underscoreIndex < baseName.Length - 1)
{
string numberPart = baseName.Substring(underscoreIndex + 1);
if (int.TryParse(numberPart, out int numericValue))
{
string newNumberPart = numericValue.ToString(newFormat);
string newFileName = $"{fileBaseNameToUse}_{newNumberPart}.png";
string newFilePath = Path.Combine(folderPath, newFileName);
if (!File.Exists(newFilePath) || newFilePath == file)
{
if (newFilePath != file)
{
File.Move(file, newFilePath);
result.FilesRenamed++;
result.ChangesMade = true;
}
}
else if (newFilePath != file)
{
result.Errors.Add($"Cannot rename '{file}' to '{newFilePath}' because the target file already exists.");
}
}
}
}
return result;
}
// Method to import and merge folders, then normalize file numbering and padding
public void ImportAndMergeFolders(string existingFolderPath, string importFolderPath)
{
// Before changes
string[] existingFilesBefore = Directory.GetFiles(existingFolderPath, "*.png");
int existingFileCountBefore = existingFilesBefore.Length;
AnalyzeAndPrepareExistingFolder(existingFolderPath);
string[] existingFiles = Directory.GetFiles(existingFolderPath, "*.png");
var existingFilesOrdered = GetOrderedFiles(existingFiles);
int maxExistingIndex = existingFilesOrdered.Keys.Any() ? existingFilesOrdered.Keys.Max() : 0;
int numDigits = maxExistingIndex.ToString().Length;
string baseName = Path.GetFileNameWithoutExtension(existingFilesOrdered.Values.FirstOrDefault() ?? "file").Split('_')[0];
string[] importFiles = Directory.GetFiles(importFolderPath, "*.png");
var importFilesOrdered = GetOrderedFiles(importFiles);
int fileIndex = maxExistingIndex + 1;
int importedFileCount = 0;
foreach (var entry in importFilesOrdered)
{
string newFileName = $"{baseName}_{fileIndex.ToString($"D{numDigits}")}.png";
string newFilePath = Path.Combine(existingFolderPath, newFileName);
File.Copy(entry.Value, newFilePath, overwrite: false);
fileIndex++;
importedFileCount++;
}
UpdateZeroPadding(existingFolderPath, baseName);
// After changes
string[] existingFilesAfter = Directory.GetFiles(existingFolderPath, "*.png");
int totalFilesAfter = existingFilesAfter.Length;
// Display results in a message box
MessageBox.Show("Operation Successful\n" +
$"Files Imported: {importedFileCount}\n" +
$"Total Files Before: {existingFileCountBefore}\n" +
$"Total Files After: {totalFilesAfter}",
"Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
// Method to analyze and prepare the existing folder for merging
private void AnalyzeAndPrepareExistingFolder(string existingFolderPath)
{
string[] existingFiles = Directory.GetFiles(existingFolderPath, "*.png");
var existingFilesOrdered = GetOrderedFiles(existingFiles);
if (!existingFilesOrdered.Any())
return;
int maxNumber = existingFilesOrdered.Keys.Max();
int maxDigits = maxNumber.ToString().Length;
string baseName = Path.GetFileNameWithoutExtension(existingFilesOrdered.Values.First()).Split('_')[0];
foreach (var entry in existingFilesOrdered)
{
string newFileName = $"{baseName}_{entry.Key.ToString(GetNumberFormat(maxDigits))}.png";
string newFilePath = Path.Combine(existingFolderPath, newFileName);
if (newFilePath != entry.Value)
File.Move(entry.Value, newFilePath);
}
}
public class SequenceFixResult
{
public int FilesRenamed { get; set; }
public bool ChangesMade { get; set; }
public List<string> Errors { get; set; } = new List<string>();
}
public string GetBaseFileNameWithinFolder(string folderPath, string searchPattern = null)
{
if (searchPattern == null) searchPattern = "*.png";
string[] files = Directory.GetFiles(folderPath, searchPattern);
if (files.Length == 0)
{
MessageBox.Show("No PNG files were found in the selected folder.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return null;
}
string fileName = Path.GetFileName(files[0]);
int underscoreIndex = fileName.LastIndexOf('_');
if (underscoreIndex != -1)
{
return fileName.Substring(0, underscoreIndex);
}
// Display error message
MessageBox.Show("A problem occurred trying to determine the base file name in the folder." +
"\n\nMake sure the images are all named and numbered like:\nWhateverBaseName_01.png" +
"\n\nThis could also be due to other PNGs in the folder that are not part of the sequence.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return null;
}
public SequenceFixResult FixDiscontinuousSequence(string folderPath, string fileBaseNameToUse = null, int startIndex = 1)
{
if (fileBaseNameToUse == null)
{
fileBaseNameToUse = GetBaseFileNameWithinFolder(folderPath: folderPath);
if (fileBaseNameToUse == null)
{
return new SequenceFixResult { Errors = { "No files found in the folder." } };
}
}
string searchPattern = $"{fileBaseNameToUse}_*.png";
string[] files = Directory.GetFiles(folderPath, searchPattern);
var orderedFiles = GetOrderedFiles(files);
SequenceFixResult result = new SequenceFixResult();
int currentIndex = startIndex;
foreach (var entry in orderedFiles)
{
string currentFileName = Path.GetFileNameWithoutExtension(entry.Value);
int underscoreIndex = currentFileName.LastIndexOf('_');
string currentNumberPart = currentFileName.Substring(underscoreIndex + 1);
int currentPaddingLength = currentNumberPart.Length; // Determine the original padding length
string expectedFileName = $"{fileBaseNameToUse}_{currentIndex.ToString($"D{currentPaddingLength}")}.png";
string expectedFilePath = Path.Combine(folderPath, expectedFileName);
if (expectedFilePath != entry.Value) // Only rename if necessary
{
try
{
File.Move(entry.Value, expectedFilePath);
result.FilesRenamed++;
result.ChangesMade = true;
}
catch (IOException ex)
{
result.Errors.Add($"Failed to rename '{entry.Value}' to '{expectedFilePath}': {ex.Message}");
}
}
currentIndex++;
}
return result;
}
public static List<Dictionary<string, object>> CheckAlphaChannel(string imagePath, bool countAll = false)
{
int visiblePixelsCount = 0;
// Create list of dictionaries to store the pixel data - Including each pixel's ARGB values and coordinates
List<Dictionary<string, object>> pixelData = new List<Dictionary<string, object>>();
try
{
using (Bitmap bitmap = new Bitmap(imagePath))
{
for (int y = 0; y < bitmap.Height; y++)
{
for (int x = 0; x < bitmap.Width; x++)
{
Color pixelColor = bitmap.GetPixel(x, y);
if (pixelColor.A != 0)
{
visiblePixelsCount++;
Dictionary<string, object> pixelInfo = new Dictionary<string, object>
{
{ "X", x },
{ "Y", y },
{ "A", pixelColor.A },
{ "R", pixelColor.R },
{ "G", pixelColor.G },
{ "B", pixelColor.B }
};
pixelData.Add(pixelInfo);
if (!countAll)
{
return pixelData;
}
}
}
}
}
return pixelData;
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
return pixelData;
}
}
}