2010-07-02 25 views

Respuesta

4

Si solo necesita el trabajo realizado, entonces SmartFTP podría ayudarlo, it also has a PHP and ASP script para obtener el tamaño total de la carpeta visitando recursivamente todos los archivos.

+0

función SmartFTP muy fresco, gracias –

+1

WinSCP hace muy buena solución, así – aaiezza

2

Puede enviar el comando LIST que debe proporcionarle una lista de archivos en el directorio y alguna información sobre ellos (bastante cierto el tamaño está incluido), que luego puede analizar y sumar.

Depende de cómo se conecta al servidor, pero si está utilizando la clase WebRequest.Ftp existe el método ListDirectoryDetails para hacerlo. Consulte here para obtener detalles y here para obtener un código de muestra.

Solo tenga en cuenta, si quiere tener el tamaño total incluyendo todos los subdirectorios, creo que tendrá que ingresar cada subdirectorio y llamarlo recursivamente, por lo que podría ser bastante lento. Puede ser bastante lento, por lo que normalmente le recomendé, si es posible, tener un script en el servidor, calcular el tamaño y devolver el resultado de alguna manera (posiblemente almacenándolo en un archivo que pueda descargar y leer).

Editar: O si solo quiere decir que estaría contento con una herramienta que lo hace por usted, creo que FlashFXP lo hace y probablemente otros clientes de FTP avanzados también lo harán. O si es un servidor Unix, tengo una memoria vaga que podría simplemente iniciar sesión y escribir ls -laR o algo así para obtener una lista recursiva de directorios.

-2

sólo tiene que utilizar el comando "TAMAÑO" ...

73

Si tiene FileZilla, puede utilizar este truco FTP:

  • clic en la carpeta (s) cuyo tamaño desea calcular
  • haga clic en Add files to queue

Esto escaneará todas las carpetas y archivos y los agregará a la cola. Luego mire el panel de cola y debajo de él (en la barra de estado) debería ver un mensaje que indica el tamaño de la cola.

+3

. De esta forma, puede obtener la cantidad total de archivos y el tamaño total sin descargar ningún archivo. El [comando FTP] (http://en.wikipedia.org/wiki/List_of_FTP_commands) utilizado por Filezilla es MLSD (recursivamente) si alguien tiene curiosidad al respecto. –

+3

Tenga en cuenta que debe tener un destino válido seleccionado en el panel del árbol del directorio local (de lo contrario _Agregar archivos a la cola_ estará atenuado). – jbaums

1

Uso el FTPS library de Alex Pilotti con C# para ejecutar algunos comandos de FTP en algunos entornos de producción. La biblioteca funciona bien, pero debe obtener recursivamente una lista de archivos en el directorio y agregar sus tamaños para obtener el resultado. Esto puede consumir bastante tiempo en algunos de nuestros servidores más grandes (a veces de 1 a 2 minutos) con estructuras de archivos complejas.

De todos modos, este es el método que utilizo con su biblioteca:

/// <summary> 
/// <para>This will get the size for a directory</para> 
/// <para>Can be lengthy to complete on complex folder structures</para> 
/// </summary> 
/// <param name="pathToDirectory">The path to the remote directory</param> 
public ulong GetDirectorySize(string pathToDirectory) 
{ 
    try 
    { 
     var client = Settings.Variables.FtpClient; 
     ulong size = 0; 

     if (!IsConnected) 
      return 0; 

     var dirList = client.GetDirectoryList(pathToDirectory); 
     foreach (var item in dirList) 
     { 
      if (item.IsDirectory) 
       size += GetDirectorySize(string.Format("{0}/{1}", pathToDirectory, item.Name)); 
      else 
       size += item.Size; 
     } 
     return size; 
    } 
    catch (Exception ex) 
    { 
     Console.WriteLine(ex.Message); 
    } 
    return 0; 
} 
13

Usted puede utilizar el comando du en lftp para este fin, como esto:

echo "du -hs ." | lftp example.com 2>&1 

Esto imprimirá la corriente tamaño del disco del directorio incl. todos los subdirectorios, en formato legible para humanos (-h) y omisión de líneas de salida para subdirectorios (-s). La salida stderr se redirige a stdout con 2>&1 para que se incluya en la salida.

Sin embargo, lftp es un software solo para Linux, por lo que para usarlo desde C# necesitaría usarlo dentro de Cygwin.

La documentación del comando lftp du falta en its manpage, pero está disponible dentro del shell lftp con el comando help du. Como referencia, copio su producción aquí:

lftp :~> help du 
Usage: du [options] <dirs> 
Summarize disk usage. 
-a, --all    write counts for all files, not just directories 
    --block-size=SIZ use SIZ-byte blocks 
-b, --bytes   print size in bytes 
-c, --total   produce a grand total 
-d, --max-depth=N  print the total for a directory (or file, with --all) 
         only if it is N or fewer levels below the command 
         line argument; --max-depth=0 is the same as 
         --summarize 
-F, --files   print number of files instead of sizes 
-h, --human-readable print sizes in human readable format (e.g., 1K 234M 2G) 
-H, --si    likewise, but use powers of 1000 not 1024 
-k, --kilobytes  like --block-size=1024 
-m, --megabytes  like --block-size=1048576 
-S, --separate-dirs do not include size of subdirectories 
-s, --summarize  display only a total for each argument 
    --exclude=PAT  exclude files that match PAT 
+2

Para autenticación echo "du -hs." | lftp -u usuario, contraseña nombre de host 2> & 1 –

+0

alternativa a cygwin es msys2 –

+1

Ahora puede usar el Subsistema de Windows para Linux (WSL) si está usando Windows 10 –

0

Más simple y manera eficaz de obtener Directorio FTP Tamaño con él está todo contenido de forma recursiva.

var size = FTP.GetFtpDirectorySize ("ftpURL", "nombre de usuario", "contraseña");

using System; 
using System.Collections.Generic; 
using System.IO; 
using System.Net; 
using System.Threading; 
using System.Threading.Tasks; 

public static class FTP 
{ 
    public static long GetFtpDirectorySize(Uri requestUri, NetworkCredential networkCredential, bool recursive = true) 
    { 
     //Get files/directories contained in CURRENT directory. 
     var directoryContents = GetFtpDirectoryContents(requestUri, networkCredential); 

     long ftpDirectorySize = default(long); //Set initial value of the size to default: 0 
     var subDirectoriesList = new List<Uri>(); //Create empty list to fill it later with new founded directories. 

     //Loop on every file/directory founded in CURRENT directory. 
     foreach (var item in directoryContents) 
     { 
      //Combine item path with CURRENT directory path. 
      var itemUri = new Uri(Path.Combine(requestUri.AbsoluteUri + "\\", item)); 
      var fileSize = GetFtpFileSize(itemUri, networkCredential); //Get item file size. 

      if (fileSize == default(long)) //This means it has no size so it's a directory and NOT a file. 
       subDirectoriesList.Add(itemUri); //Add this item Uri to subDirectories to get it's size later. 
      else //This means it has size so it's a file. 
       Interlocked.Add(ref ftpDirectorySize, fileSize); //Add file size to overall directory size. 
     } 

     if (recursive) //If recursive true: it'll get size of subDirectories files. 
      Parallel.ForEach(subDirectoriesList, (subDirectory) => //Loop on every directory 
      //Get size of selected directory and add it to overall directory size. 
     Interlocked.Add(ref ftpDirectorySize, GetFtpDirectorySize(subDirectory, networkCredential, recursive))); 

     return ftpDirectorySize; //returns overall directory size. 
    } 
    public static long GetFtpDirectorySize(string requestUriString, string userName, string password, bool recursive = true) 
    { 
     //Initialize Uri/NetworkCredential objects and call the other method to centralize the code 
     return GetFtpDirectorySize(new Uri(requestUriString), GetNetworkCredential(userName, password), recursive); 
    } 

    public static long GetFtpFileSize(Uri requestUri, NetworkCredential networkCredential) 
    { 
     //Create ftpWebRequest object with given options to get the File Size. 
     var ftpWebRequest = GetFtpWebRequest(requestUri, networkCredential, WebRequestMethods.Ftp.GetFileSize); 

     try { return ((FtpWebResponse)ftpWebRequest.GetResponse()).ContentLength; } //Incase of success it'll return the File Size. 
     catch (Exception) { return default(long); } //Incase of fail it'll return default value to check it later. 
    } 
    public static List<string> GetFtpDirectoryContents(Uri requestUri, NetworkCredential networkCredential) 
    { 
     var directoryContents = new List<string>(); //Create empty list to fill it later. 
                //Create ftpWebRequest object with given options to get the Directory Contents. 
     var ftpWebRequest = GetFtpWebRequest(requestUri, networkCredential, WebRequestMethods.Ftp.ListDirectory); 
     try 
     { 
      using (var ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse()) //Excute the ftpWebRequest and Get It's Response. 
      using (var streamReader = new StreamReader(ftpWebResponse.GetResponseStream())) //Get list of the Directory Contentss as Stream. 
      { 
       var line = string.Empty; //Initial default value for line. 
       do 
       { 
        line = streamReader.ReadLine(); //Read current line of Stream. 
        directoryContents.Add(line); //Add current line to Directory Contentss List. 
       } while (!string.IsNullOrEmpty(line)); //Keep reading while the line has value. 
      } 
     } 
     catch (Exception) { } //Do nothing incase of Exception occurred. 
     return directoryContents; //Return all list of Directory Contentss: Files/Sub Directories. 
    } 
    public static FtpWebRequest GetFtpWebRequest(Uri requestUri, NetworkCredential networkCredential, string method = null) 
    { 
     var ftpWebRequest = (FtpWebRequest)WebRequest.Create(requestUri); //Create FtpWebRequest with given Request Uri. 
     ftpWebRequest.Credentials = networkCredential; //Set the Credentials of current FtpWebRequest. 

     if (!string.IsNullOrEmpty(method)) 
      ftpWebRequest.Method = method; //Set the Method of FtpWebRequest incase it has a value. 
     return ftpWebRequest; //Return the configured FtpWebRequest. 
    } 
    public static NetworkCredential GetNetworkCredential(string userName, string password) 
    { 
     //Create and Return NetworkCredential object with given UserName and Password. 
     return new NetworkCredential(userName, password); 
    } 
} 
Cuestiones relacionadas