Sweet!
Couple of comments:
1. I love the way you structure you classes. Almost identical to my
own way of doing this.
2. I would use the members of the System.IO namespace instead of
relying on string splitting. I would do it like this:
---
class DirClr
{
private string path;
private FileInfo[] files;
private DirectoryInfo dir;
public DirClr(string rootPath)
{
this.path = rootPath;
dir = new DirectoryInfo(rootPath);
if (!dir.Exists)
throw new ArgumentException("Target directory does not exist!");
this.files = dir.GetFiles();
}
private DirectoryInfo CreateDir(string dirName)
{
dir = new DirectoryInfo(dirName);
return CreateDir(dir);
}
private DirectoryInfo CreateDir(DirectoryInfo dir)
{
if (!dir.Exists)
dir.Create();
return dir;
}
private DirectoryInfo GetExtension(FileInfo file)
{
string ext = file.Extension.Replace(".", "");
return CreateDir(path + "\\" + ext);
}
public void Run()
{
foreach (FileInfo file in this.files)
{
DirectoryInfo childDir = GetExtension(file);
file.MoveTo(childDir.FullName + "\\" + file.Name);
}
}
}
---
More improvements might be likely because I wrote this in like five
min. :-)
On Jul 27, 12:08 pm, Processor-Dev1l <[email protected]>
wrote:
> Hi, guys. Since I had moved to Windows again, I have found my desktop
> messed up with a lot of files (links, pdf's, exe's, etc). So I made a
> code to sort this mess in directories...
>
> using System;
> using System.IO;
>
> namespace DirectoryCleaner
> {
> class Program
> {
> public static void Main(string[] args)
> {
> try
> {
> DirClr s = new DirClr(args[0]);
> s.Run();
> } catch(Exception e)
> {
> Console.WriteLine(e.Message);
> Console.WriteLine("Usage:\nDirectoryCleaner
> <directory>");
> }
> }
> }
> class DirClr
> {
> public DirClr(string path)
> {
> this.path = path + "\\data";
> this.createDir(this.path);
> this.files = Directory.GetFiles(path);
>
> }
> void createDir(string name)
> {
> if(!Directory.Exists(this.path+"\\"+name))
>
> Directory.CreateDirectory(this.path+"\\"+name);
> }
> void moveFile(string name, string dir)
> {
> string fileName = this.nameOfFile(name);
> File.Move(name, this.path+"\\"+dir+"\\"+fileName);
> }
> string parse(string name)
> {
> string[] data = name.Split('.');
> return data[data.Length - 1];
> }
> string nameOfFile(string name)
> {
> string[] path = name.Split('\\');
> return path[path.Length - 1];
> }
> public void Run()
> {
> foreach(string file in this.files)
> {
> string dir = this.parse(file);
> this.createDir(dir);
> this.moveFile(file, dir);
> }
> }
> string path;
> string[] files;
> }
>
>
>
> }- Hide quoted text -
>
> - Show quoted text -