16

How do I determine the size of a text file?

I know that I could just count characters, but the file will be several MB's large.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
John Wheal
  • 9,908
  • 6
  • 29
  • 39

4 Answers4

50
Dim myFile As New FileInfo("file.txt")
Dim sizeInBytes As Long = myFile.Length
Jaykul
  • 15,370
  • 8
  • 61
  • 70
Dennis Traub
  • 50,557
  • 7
  • 93
  • 108
19
Dim size As Long = FileLen("file.txt")

https://msdn.microsoft.com/en-us/library/microsoft.visualbasic.filesystem.filelen

Slai
  • 22,144
  • 5
  • 45
  • 53
3

The use of file can be dangerous as it is also the name of a class. It is better to code it as follows:

Dim myFile As New FileInfo("file.txt")
Dim sizeInBytes As Long = myFile.Length
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • 1
    This is true enough, but you really should come up with a better name than `myFile`. It's a good opportunity to write something *descriptive*. IntelliSense makes using long names easy enough. – Cody Gray - on strike Jul 12 '13 at 21:44
  • 1
    -1 for ripping off the code in the answer before it. This is pretty much a direct copy of the accepted answer. – AStopher Nov 09 '14 at 15:30
  • 5
    +1 because using reserved words (or anything like it) is an awful practice and I'm glad this comment stopped me from doing so. – Isaac May 01 '15 at 22:53
  • 3
    This should be an edit or a comment to the previous answer, not a separate answer. -1 – digawp Jul 29 '15 at 02:23
-4

The code from the other answer does not check the correct size of the file:

Dim myFile As New FileInfo("file.txt")
Dim sizeInBytes As Long = MyFile.Length 

Try this code instead

Dim infoReader As System.IO.FileInfo = _
    My.Computer.FileSystem.GetFileInfo("C:\testfile.txt")
MsgBox("File C:\testfile.txt is " & infoReader.Length & " bytes.")

It is from How to: Determine a File's Size in Visual Basic (MSDN).

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mubarak
  • 1
  • 3
  • 1
    Why would the first code snippet not work? The file specification is different for the two code snippets, "file.txt" for the first code snippet (relative file specification) and "C:\testfile.txt" for the second (absolute file specification). The first one depends on the current directory. Wouldn't the first code snippet work if it used "C:\testfile.txt" instead of "file.txt"? – Peter Mortensen Dec 21 '13 at 20:05
  • 2
    This answer is just plain wrong. ***The only reason the first code snippet won't work is if you do not have the permissions to read the file. The first code snippet is just a shortened version of the second, further rendering your 'does not work' invalid..*** – AStopher Nov 09 '14 at 15:32