Click here to Skip to main content
15,901,921 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Good day to all,

Anyone know how to retrieve the file size of a file? or as much as possible all information of the file?

In getting the size of the file, I am using FileStream. But not all the files can be accessed. some problems are because of it is being used by another process, or access is denied. How to ease these problems?

Hopefully you can give me the actual code.

Thanks a lot!! :)
Posted

here are the codes i used.

file = "C:\mytext.txt";

using (FileStream Fsize = File.OpenRead(file)){
FileInfo.Size = (double)Fsize.Length;
}

: to format the size

private string FormatSize(double size)
{
string[] sizes = {"B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"};
double formattedSize = size;
Int32 sizeIndex = 0;
while (formattedSize >= 1024 && sizeIndex < sizes.Length)
{
formattedSize /= 1024;
sizeIndex++;
}
return Math.Round(formattedSize, 2).ToString() + " " + sizes[sizeIndex];
}

What i want to have is that retrieve the filesize of the file, even if it is open
or currently using by other process. Just like what windows Os has, when you right click on the file, you get its information including the filesize.

Thanks!
 
Share this answer
 
v2
Hello,

You could do it by using the file FileInfo class rather than loading your file in a FileStream.
The FileInfo class will work even if the file is in use and will not throw an exception. If you use File.OpenRead(file)it will not work.

Here is a sample code:

C#
string file = @"c:\pagefile.sys";

FileInfo f = new FileInfo(file);
long size = f.Length;

double formattedSize = size;

string[] sizes = {"B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"};
Int32 sizeIndex = 0;
while (formattedSize >= 1024 && sizeIndex < sizes.Length)
{
    formattedSize /= 1024;
    sizeIndex++;
}
MessageBox.Show(Math.Round(formattedSize, 2).ToString() + " " + sizes[sizeIndex]);


Valery.
 
Share this answer
 
In addition to Abhinav's solution you can use FileInfo class' Lenght Property to get size of a file...

Here is MSDN link[^]
 
Share this answer
 
This kind of question is asked often here on the forum. By a bit better searching you coulkd have found the answer

Use FileInfo for information about a file.
To prevent a file being used by another process:
see solution 2 in link Deleting the files within the folder dynamically using asp.net[^]
 
Share this answer
 
Make sure that file is not open in another program.

Other than that, paste some of your code here - without looking at code, its quite impossible to answer your question.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900