Hi,
I need to develop a windows application in C#, where I have to get all the hierarchy of folders, sub folders and files listed in a database in the order they are on the disk. The place where i am stuck up adding the same hierarchy to the database.I am not getting the exact parent and child relationship of the ids of folders and subfolders from my code. Please suggest.
My code is as follows :
public void PopulateTreeView(string directoryValue, TreeNode parentNode)
{
string[] directoryArray = Directory.GetDirectories(directoryValue);
try
{
if (directoryArray.Length != 0)
{
foreach (string directory in directoryArray)
{
substringDirectory = directory.Substring(directory.LastIndexOf('\\') + 1, directory.Length - directory.LastIndexOf('\\') - 1);
TreeNode myNode = new TreeNode(substringDirectory);
parentNode.Nodes.Add(myNode);
string path = Convert.ToString(directory.Remove(directory.LastIndexOf("\\")));
string[] files = Directory.GetFiles(directory);
string[] directories = Directory.GetDirectories(directory);
if (files.Length > 0)
{
collectFileInfo(ID,ParentID, directory);
}
else
if (directories.Length > 0)
{
collectFolderInfo(ID,ParentID, directory);
}
ParentID = ParentID + 1;
PopulateTreeView(directory, myNode);
}
}
}
catch (UnauthorizedAccessException)
{
parentNode.Nodes.Add("Access denied");
}
}
private void collectFileInfo(Int32 ID, Int32 ParentID, String dir)
{
String[] files = Directory.GetFiles(dir);
if (files.Length > 0)
{
foreach (String file in files)
{
FileInfo File1 = new FileInfo(file);
String fileName = File1.Name;
String filePath = File1.FullName;
String fileSize = File1.Length.ToString();
String fileExtension = File1.Extension;
String fileCreated = File1.LastWriteTime.ToString();
WriteToTable(ParentID, fileName, filePath, true);
}
}
else
{
}
}
private void collectFolderInfo(Int32 ID, Int32 ParentID, String dir)
{
String[] directories = Directory.GetDirectories(dir);
if (directories.Length > 0)
{
foreach (String Direc in directories)
{
DirectoryInfo dir1 = new DirectoryInfo(Direc);
string dirName = dir1.Name;
string path = dir1.FullName;
WriteToTable(ParentID, dirName, path, false);
}
}
else
{
}
}
private void WriteToTable(Int32 ParentID, string FileName,string FilePath,Boolean IsFile)
{
String conStr = "Data Source=.;Initial Catalog=DBNormalizerTest;Integrated Security=True";
SqlConnection conn = new SqlConnection(conStr);
SqlCommand cmd = new SqlCommand();
conn.Open();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Insert into tblFiles values(" + ID + "," + "'" + Convert.ToInt32(ParentID) + "'" + "," + "'" + FileName + "'" + "," + "'" + FilePath + "'" + "," + "'" + Convert.ToBoolean(IsFile) + "'" + ")";
cmd.ExecuteNonQuery();
conn.Close();
ID = ID + 1;
}
Anurag