- Функция GetFileSize
- Get File size and directory size from command line
- GetFileSize function (fileapi.h)
- Syntax
- Parameters
- Return value
- Remarks
- How do you get the file size in C#?
- 7 Answers 7
- Not the answer you’re looking for? Browse other questions tagged c# filesize or ask your own question.
- Linked
- Related
- Hot Network Questions
- Subscribe to RSS
- Windows command for file size only
- 12 Answers 12
Функция GetFileSize
Функция GetFileSize извлекает размер указанного файла. Размер файла, который может быть сообщен при помощи этой функции ограничивается значением двойного слова (DWORD).
Чтобы извлечь размер файла, который является большим, чем значение двойного слова (DWORD), используйте функцию GetFileSizeEx .
[in] Дескриптор файла, размер которого должен возвратиться. Этот дескриптор должен быть создан или с правом доступа GENERIC_READ или GENERIC_WRITE . Для получения дополнительной информации, см. статью Защита файла и права доступа.
[out] Указатель на переменную, в которой возвращается старшее слово размера файла . Этот параметр может быть ПУСТО (NULL), если приложению не требуется старшего слова.
Если функция завершается успешно, возвращаемое значение — младшая часть двойного слова размера файла, и если параметр lpFileSizeHigh — не ПУСТО (NULL), функция помещает старшую часть двойного слова размера файла в переменную, на которую указывает этот параметр.
Если функция завершается ошибкой, и lpFileSizeHigh равен ПУСТО (NULL), возвращаемое значение — INVALID_FILE_SIZE . Чтобы получить дополнительные данные об ошибке, вызовите GetLastError .
Если функция завершается ошибкой, и lpFileSizeHigh — не ПУСТО (NULL), возвращаемое значение — INVALID_FILE_SIZE , а GetLastError возвратит другое значение, а не NO_ERROR .
Нельзя использовать функцию GetFileSize с дескриптором не искомого устройства типа канала или коммуникационного устройства. Чтобы выяснить тип файла для параметра hFile, используйте функцию GetFileType .
Функция GetFileSize извлекает несжатый размер файла. Используйте функцию GetCompressedFileSize , чтобы получить сжатый размер файла.
Обратите внимание! на то, что это, если возвращаемое значение — INVALID_FILE_SIZE и параметр lpFileSizeHigh — не ПУСТО (NULL), приложение должно вызвать GetLastError, чтобы выяснить, успешно ли завершилась функция или завершилась ошибкой. Причина, по которой функция, может оказаться завершенной ошибкой, состоит в том, что lpFileSizeHigh может быть не-ПУСТО (NULL), или размер файла мог быть 0xffffffff. В этой ситуации, GetLastError возвратит NO_ERROR после успешного завершения. Нижеследующий типовой код иллюстрирует этот момент: |
Размещение и совместимость GetFileSize
Get File size and directory size from command line
How to find the size of a file
In Windows, we can use dir command to get the file size.
But there is no option/switch to print only the file size.
Get size for all the files in a directory
Dir command accepts wild cards. We can use ‘*” to get the file sizes for all the files in a directory.
We can also get size for files of certain type. For example, to get file size for mp3 files, we can run the command ‘dir *.mp3‘.
The above command prints file modified time also. To print only the file name and size we can run the below command from a batch file.
Save the above commands to a text file, say filesize.bat, and run it from command prompt.
Get directory size
There’s no Windows built in command to find directory size.В But there is a tool called diruse.exe which can be used to get folder size. This tool is part of XP support tools.В This command can be used to get directory size. This command’s syntax is given below.
As you can see in the above example, diruse prints the directory size in bytes and it also prints the number of files in the directory(it counts the number of files in the sub folders also)
To get the directory size in mega bytes we can add /M switch.
Though the tool is intended for XP and Server 2003, I have observed that it works on Windows 7 also.В The above examples were indeed from a Windows 7 computer.
Jan-18-2012
I validated/downloaded/started to install.
The setup software said, “This program has known compatibility issues.”
(I will probably continue anyway, in hopes that SOME of the software may work.)
I’m guessing that the problem is that I am running Windows 7 64-Bit.
Am I correct, that YOU are using Windows 7 32Bit ?
Jan-18-2012—followup
The attempt to instal; anyway, (in spite of compatibility problem) aborted,
It said, approximately, “can only be installed on WinXP”.
Try extracting the files instead of installing them. Command for this is something like this.
installer.exe /x
My machine is also 64 bit and is running on 64-bit OS.
In Windows7, right-click on the installer, select Troubleshoot compatibility, select Troubleshoot program, select first option “This program worked in earlier versions of Windows but won’t install or run now”, select Windows XP (Service Pack 2), select Start the program, ignore the compatibility issue warning by clicking Run program
please suggest how to get size in GB.MB useing DOS
get a calculator divide by 1024
You can get the list of the directories and their size using the following command:
The following command should do and output the file as csv
Dir/s |Find /V “/”> Folder_info.csv
To get the file use
then save as and save where you want.
The ‘for’ command can return the size of a file using %
zI.
Type ‘for /?’ at a command prompt for the details.
GetFileSize function (fileapi.h)
Retrieves the size of the specified file, in bytes.
It is recommended that you use GetFileSizeEx.
Syntax
Parameters
A handle to the file.
A pointer to the variable where the high-order doubleword of the file size is returned. This parameter can be NULL if the application does not require the high-order doubleword.
Return value
If the function succeeds, the return value is the low-order doubleword of the file size, and, if lpFileSizeHigh is non-NULL, the function puts the high-order doubleword of the file size into the variable pointed to by that parameter.
If the function fails and lpFileSizeHigh is NULL, the return value is INVALID_FILE_SIZE. To get extended error information, call GetLastError. When lpFileSizeHigh is NULL, the results returned for large files are ambiguous, and you will not be able to determine the actual size of the file. It is recommended that you use GetFileSizeEx instead.
If the function fails and lpFileSizeHigh is non-NULL, the return value is INVALID_FILE_SIZE and GetLastError will return a value other than NO_ERROR.
Remarks
You cannot use the GetFileSize function with a handle of a nonseeking device such as a pipe or a communications device. To determine the file type for hFile, use the GetFileType function.
The GetFileSize function retrieves the uncompressed size of a file. Use the GetCompressedFileSize function to obtain the compressed size of a file.
Note that if the return value is INVALID_FILE_SIZE (0xffffffff), an application must call GetLastError to determine whether the function has succeeded or failed. The reason the function may appear to fail when it has not is that lpFileSizeHigh could be non-NULL or the file size could be 0xffffffff. In this case, GetLastError will return NO_ERROR (0) upon success. Because of this behavior, it is recommended that you use GetFileSizeEx instead.
Transacted Operations:В В If there is a transaction bound to the file handle, then the function returns information for the isolated file view.
In WindowsВ 8 and Windows ServerВ 2012, this function is supported by the following technologies.
How do you get the file size in C#?
I need a way to get the size of a file using C#, and not the size on disk. How is this possible?
Currently I have this loop
Will this return the size or the size on disk?
7 Answers 7
FileInfo.Length will return the length of file, in bytes (not size on disk), so this is what you are looking for, I think.
If you have already a file path as input, this is the code you need:
FileInfo.Length will do the trick (per MSDN it «[g]ets the size, in bytes, of the current file.») There is a nice page on MSDN on common I/O tasks.
MSDN FileInfo.Length says that it is «the size of the current file in bytes.»
My typical Google search for something like this is: msdn FileInfo
It returns the file contents length
Size on disk might be different, if you move the file to another filesystem (FAT16, NTFS, EXT3, etc)
As other answerers have said, this will give you the size in bytes, not the size on disk.
The FileInfo class’ Length property returns the size of the file (not the size on disk). If you want a formatted file size (i.e. 15 KB) rather than a long byte value you can use CSharpLib, a package I’ve made that adds more functionality to the FileInfo class. Here’s an example:
Not the answer you’re looking for? Browse other questions tagged c# filesize or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.4.16.39093
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Windows command for file size only
Is there a Windows command that will output the size in bytes of a specified file like this?
I know that the dir command outputs this information, but it outputs other information also.
I could easily write such a program, but I would prefer to use a native Windows command if possible, or only what is available in a fresh install of Windows XP.
12 Answers 12
If you are inside a batch script, you can use argument variable tricks to get the filesize:
This gives results like the ones you suggest in your question.
at the command prompt for all of the crazy variable manipulation options. Also see this article for more information.
Edit: This only works in Windows 2000 and later
znI . – Patrick Cuff Jan 27 ’09 at 16:41
z variables refer specifically to a file passed as an argument, so will be looking up their values from the filesystem, rather than a dynamic stream of bytes. – Mike Houston Aug 5 ’16 at 17:39
zn1 wasn’t working in a console ( 1 != I xD) – kayleeFrye_onDeck Oct 15 ’19 at 21:16
If you don’t want to do this in a batch script, you can do this from the command line like this:
Ugly, but it works. You can also pass in a file mask to get a listing for more than one file:
Will display the size, file name of each .DOC file.
Use a function to get rid off some limitation in the
z operator. It is especially useful with a for loop:
z1/1024 – David Doumèche Mar 18 ’14 at 2:59
The forfiles command runs command c for each file m in directory p .
The variable @fsize is replaced with the size of each file.
If the file C:\Temp\file1.txt is 27 bytes, forfiles runs this command:
Which prints 27 to the screen.
As a side-effect, it clears your screen as if you had run the cls command.
Since you’re using Windows XP, Windows PowerShell is an option.
or as a function
Create a file named filesize.cmd (and put into folder C:\Windows\System32):
In a batch file, the below works for local files, but fails for files on network hard drives
However, it’s inferior code, because it doesn’t work for files saved on a network drive (for example, \\Nas\test.jpg and \\192.168.2.40\test.jpg ). The below code works for files in any location, and I wrote it myself.
I’m sure there are more efficient ways of doing this using VBScript, or PowerShell or whatever, but I didn’t want to do any of that; good ol’ batch for me!
zI – trindflo Mar 18 ’20 at 19:23
The following command finds folders that are greater than 100 MB in size on the D: drive:
The /s option causes subdirectories to be searched, the /m option displays disk usage in megabytes, the /q:100 option causes folders that are greater than 100 MB to be marked, and the /d option displays only folders that exceed the threshold specified by /q.
Use the diskuse command to find files over a certain size. The following command displays files over 100 MB in size on the D: drive:
The /x:104857600 option causes files over 104,857,600 bytes to be displayed and is valid only if you include the /v option (verbose). The /s option means subdirectories from the specified path (in this case, the D: drive) are searched.