Cristi
Background Worker giving exceptions.
The main logic is here
string getReadableSize(long sib) {
string[] sizeSuffixes = { "B", "KB", "MB", "GB", "TB", "PB" };
int i = 0;
double size = sib;
while (size >= 1024 && i < sizeSuffixes.Length - 1) { size /= 1024; i++; }
return $"{size:0.##} {sizeSuffixes[i]}";
}
string getSelectedItemExtension() {
foreach (StackPanel item in FileList.SelectedItems) {
if (item.Children[1] is Label label) {
string path = Path.Combine(CurrentPath, label.Content.ToString());
if(File.Exists(path)) return new FileInfo(path).Extension;
else if(Directory.Exists(path)) return "Folder";
}
} return null;
}
async Task<long> getDirSize(string path) {
long res = 0;
try {
foreach (string file in Directory.GetFiles(path)) res += new FileInfo(file).Length;
foreach (string dir in Directory.GetDirectories(path)) res += await getDirSize(dir);
} catch{}
return res;
}
async Task<string> getSelectionSize() {
long res = 0;
foreach(StackPanel item in FileList.SelectedItems) {
if (item.Children[1] is Label label) {
string path = Path.Combine(CurrentPath,label.Content.ToString());
if(Directory.Exists(path)) res += await getDirSize(path);
else if(File.Exists(path)) res += new FileInfo(path).Length;
}
} return getReadableSize(res);
}
void FileList_SelectionChanged(object sender, SelectionChangedEventArgs e) {
if (FileList.SelectedItems.Count == 0) {
CurrentItemSize = "Size: --";
CurrentItemType = "Type: --";
} else {
CurrentItemSize = "Size: Calculating...";
CurrentItemSize = getSelectionSize().Result;
if (FileList.SelectedItems.Count == 1) CurrentItemType = $"Type: {getSelectedItemExtension()}";
else CurrentItemType = "Type: --";
}
}
81 replies
Background Worker giving exceptions.
@🧨 New Years Mayor McCheese 🧨
I'm sorry for the ping but I added the async and Task logic but it still doesn't work, my application freezes after I select an item until it's done calculating the size, what did I do wrong?
81 replies