如何在C# Windows中获取文件大小、文件名和文件扩展名?

6

我是一名新手,正在学习C#.net。请问如何在Windows系统中使用C#获取文件大小、文件名和文件扩展名?

我正在使用C#中的打开文件对话框,但只能获取文件路径,不知道如何获取文件名和大小。

以下是我的代码:

openFileDialog1.ShowDialog();

openFileDialog1.Title = "Select The File";
openFileDialog1.InitialDirectory = "C:";
openFileDialog1.Multiselect = false;
openFileDialog1.CheckFileExists = false;

if (openFileDialog1.FileName != "")
 {
  txtfilepath1.Text = openFileDialog1.FileName;
  var fileInfo = new FileInfo(openFileDialog1.FileName);
  lblfilesize1.Text = Convert.ToString(openFileDialog1.FileName.Length);  

  lblfilesize=
  lblfilename=    
 }
3个回答

16

3
您可以使用FileInfo类。文件信息
using System;
using System.IO;

class Program
{
    static void Main()
    {
    // The name of the file
    const string fileName = "test.txt";

    // Create new FileInfo object and get the Length.
    FileInfo f = new FileInfo(fileName);
    long s1 = f.Length;

    // Change something with the file. Just for demo.
    File.AppendAllText(fileName, " More characters.");

    // Create another FileInfo object and get the Length.
    FileInfo f2 = new FileInfo(fileName);
    long s2 = f2.Length;

    // Print out the length of the file before and after.
    Console.WriteLine("Before and after: " + s1.ToString() +
        " " + s2.ToString());

    // Get the difference between the two sizes.
    long change = s2 - s1;
    Console.WriteLine("Size increase: " + change.ToString());
    }
}

关于扩展名,您可以使用Path.GetExtension()函数。



网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接