Top community members
All Wiki Articles Create Wiki Article

Have you ever heard about encyclopedia for code?

What about: Wiki for Code project?

* because I've tried to share code and my solutions on different services and it was removed or I was unwelcomed
   - maybe it wasn't good place, but this one is.

if you think you have solution that can help someone, you are welcome to share this solution - Click here

C# / .NET - get file size

0 contributions
5 points

In this article, we're going to have a look at how to get file size in C# / .NET.

Quick overview:

FileInfo file = new FileInfo(@"C:\path\to\file.txt"); // using System.IO;
int fileSize = file.Length;

Look on below code to see practical usage example:

1. FileInfo class example

In presented solution FileInfo class was used with Length property that returns filze size.

Note: if file was modified after FileInfo object was created Refresh() method should be called on the object to get current file inforamtions.

using System;
using System.IO;

public static class Program
{
	public static void Main(string[] args)
	{
		string path = @"C:\path\to\file.txt";

		FileInfo info = new FileInfo(path);
		Console.WriteLine("File size: " + info.Length + " bytes");
	}
}

Output:

File size: 46 bytes

2. File.Open method with Length property example

In some cases when we use Length property with specific stream, we need to be sure that the property is implemented - for File.Open method result it is.

Note: this approach is useful when we have opened stream.

using System;
using System.IO;

public class Program
{
	public static void Main(string[] args)
	{
		string path = @"C:\path\to\file.txt";

		using (FileStream stream = File.Open(path, FileMode.Open))
		{
			Console.WriteLine("File size: " + stream.Length + " bytes");
		}
	}
}

Output:

File size: 46 bytes

References

  1. FileInfo.Length Property - Microsoft Docs
0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more