views:

1010

answers:

1

How to get the File Directory of a file (C:\myfolder\subfoler\mydoc.pdf). I also want to add the size of the subfolders, and finally the main folder size. This is for a .NET CLR that I need to integrate with SQL Server 2005 for a SSRS report.

Thanks.

+2  A: 

You can use GetDirectoryName, to get only the directory path of the file:

using System.IO;
string directoryName = Path.GetDirectoryName(@"C:\myfolder\subfolder\mydoc.pdf");
// directoryName now contains "C:\myfolder\subfolder"

For calculating the directory and subdirectory size, you can do something like this:

public static long DirSize(DirectoryInfo d) 
{    
    long Size = 0;    
    // Add file sizes.
    FileInfo[] fis = d.GetFiles();
    foreach (FileInfo fi in fis) 
    {      
        Size += fi.Length;    
    }
    // Add subdirectory sizes.
    DirectoryInfo[] dis = d.GetDirectories();
    foreach (DirectoryInfo di in dis) 
    {
        Size += DirSize(di);   
    }
    return(Size);  
}
CMS
I have a problem with the long Data Type when integrating this with SQL Server Assembly. Any replacement for long that is compatible with SQL Server?
MarlonRibunal
Long is what you should use in your C# code - you need to find the most appropriate data type to match it to in the db. I can't check now, but I'm positive there's an appropriate 64 bit integer type.
Jon Skeet
Right, Long can be mapped to SQL as BigInt type, 64 bit integer...
CMS
I'm getting error "CREATE FUNCTION for "DirSize" failed because T-SQL and CLR types for parameter "@dir" do not match."My CREATE Function Statement is:CREATE FUNCTION DirSize(@dir VARCHAR(MAX))RETURNS BIGINT EXTERNAL NAME getdirsize.ShowDirSize.DirSizegetdirsize is the name of my sql assembly
MarlonRibunal
It looks like the datatype problem is with the "dir" parameter, presumably the string path, rather than with the number. Are you passing it the right thing?
Khoth
@KhothWhat Data Type is compatible with DirectoryInfo?
MarlonRibunal