Recently, the fileupload control needs to be used in an Asp.net 3.5 project to read the content in a text file. Our normal idea is to use the fileupload control to select a file, read the absolute path displayed by the fileupload control in the background, and finally perform file operations under the absolute path. However, when selecting a text file, you may not be able to obtain the complete file path. You can only retrieve the file name (IE8 and firefox3.0 are the same ). In my opinion, ASP. net2.0 requires the complete file path, as long as uploadfile. postedfile. filename is enough, but now why only the file name is available? I guess it may be a bug under ASP. net3.5. Then google it and finally find a more reliable article. Article That is, this article. Then I followed and debugged the solution path. getfilename (uploadfile. postedfile. filename) with confidence. I relied on it and the file path was still wrong. Why is it wrong? I chose a text file on the desktop, and then took a path under the Installation File common7 folder on the D Drive of vs2008 in the background (you can try it yourself ). When I was speechless and Google was fruitless, I had to replace it with the HTML upload control and write several lines of JavaScript. Code The problem can be solved perfectly this time. I can't believe it when debugging it. Well... another new problem was found (you can check this article. "fakepath" replaces the folder path under a specific drive letter ). Through these two articles, we found that they are consistent on the basis of browser analysis, which is understandable. In addition, after setting the browser security options according to the method in the second article, the problem is fixed. However, we still cannot meet the requirements. If common users do not know how to set browser settings, or they need to set browser security, but what should they do if they consider to discard settings due to other external factors? Do you want to add instructions so that each user must modify the settings of his or her browser when uploading files? Obviously not desirable. In fact, we also have a work ing method (for the server control). It is very simple to use the filebytes attribute of the upload control, as shown below:
Byte [] Data = This . Fucontrol. filebytes; // Fucontrol upload Control
Then convert the binary array to the string we need. StringTxtcontent=System. Text. encoding. getencoding ("Gb2312"). Getstring (data,0, Data. Length );//Convert a binary array to a string
PS: I have only tried converting text files from binary to strings, but not other types of files. If you want to read other types of file content, but the binary file cannot be directly converted to the form you need, please use this method with caution.