简体   繁体   English

FileInfo.Length不能始终为我提供正确的文件大小

[英]FileInfo.Length is not giving me the correct file size always

I am facing a very strange issue with FileInfo and the Length property. 我面临FileInfoLength属性的一个非常奇怪的问题。 I am writing a server that responds to calls to send files (mainly images) to the clients. 我正在编写一个服务器,以响应将文件(主要是图像)发送到客户端的调用。 I want to send the file size to the client before I send the actual file. 我想在发送实际文件之前将文件大小发送给客户端。 I am using FileInfo to find the file size but strangely it does not give me the correct size every time. 我正在使用FileInfo查找文件大小,但奇怪的是,它每次都没有给我正确的大小。 Put differently, for the same file I receive different sizes, sometimes less than the actual size and sometimes correct (but never more than the actual size). 换句话说,对于同一个文件,我收到的大小不同,有时小于实际大小,有时更正(但绝不大于实际大小)。 What makes the problem even more strange, if I copy the same code to a new project (not a server, just a test project) it works fine and gives correct answers. 是什么让问题更奇怪,如果我将相同的代码复制到一个新项目(不是服务器,只是一个测试项目)中,它可以很好地工作并给出正确的答案。 The server use threads so multiple clients can connect (the test project doesn't) but I don't think that this has anything to do with FileInfo . 服务器使用线程,因此多个客户端可以连接(测试项目无法连接),但是我认为这与FileInfo没有任何关系。 Here is my code: 这是我的代码:

String fullFilePath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\" + imageName;
FileInfo file1 = new FileInfo(fullFilePath);
Console.Writeline("File Size: {0}", file1.Length);

Very basic code! 很基本的代码! My images are small in the range of 4 to 10 Kbytes only. 我的图像很小,只有4到10 KB。 Am I doing something wrong? 难道我做错了什么? Any suggestions? 有什么建议么?

I got it after all! 毕竟我明白了! The problem was not in the FileInfo class, the problem was a concept problem in my client server communication. 问题不在FileInfo类中,而是我的客户端服务器通信中的概念问题。 The images originally are not on the server, they come from another clients. 映像最初不在服务器上,它们来自其他客户端。 What was happening is that a client was sending an image to the server, and a request to get this image was reaching the server from another client but before the server actually finished saving the image on the disk. 发生的情况是,一个客户端正在将映像发送到服务器,并且获取该映像的请求已从另一个客户端到达服务器,但是服务器实际完成将映像保存到磁盘之前。 Therefore the FileInfo was getting the Length of the currently saved bytes and not the total bytes of the file. 因此, FileInfo获取的是当前保存字节的Length ,而不是文件的总字节数。

The solution was as follows: when a file was sent to the server, allow some time (for example 1 second) for the server to finish the saving process before this file can become ready to be downloaded by other clients. 解决方案如下:将文件发送到服务器后,请等待一段时间(例如1秒),让服务器完成保存过程,然后此文件才可以被其他客户端下载。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM