如何从C#目录中读取最新文件

时间:2013-12-04 08:41:06

标签: c# asp.net

我可以获取最新的文件信息属性

 var Filepath  =    directory.GetFiles("myPattern").OrderByDescending(f => f.LastWriteTime).First();

HttpPostedFile myFile = Filepath;

如何阅读此文件的内容? 错误:无法将文件信息转换为文件 下面是具有属性的类文件我试图将最新文件分配给下面的类文件。 HttpPostedFile myFile = Fileupload1.postedfile; //不抛错误 HttpPostedFile myFile = Filepath; //投掷错误 错误:无法将文件信息转换为文件

public sealed class HttpPostedFile 
{ 
// Summary: 
// Gets the size of an uploaded file, in bytes. 
// 
// Returns: 
// The file length, in bytes. 
public int ContentLength { get; } 
// 
// Summary: 
// Gets the MIME content type of a file sent by a client. 
// 
// Returns: 
// The MIME content type of the uploaded file. 
public string ContentType { get; } 
// 
// Summary: 
// Gets the fully qualified name of the file on the client. 
// 
// Returns: 
// The name of the client's file, including the directory path. 
public string FileName { get; } 
// 
// Summary: 
// Gets a System.IO.Stream object that points to an uploaded file to prepare 
// for reading the contents of the file. 
// 
// Returns: 
// A System.IO.Stream pointing to a file. 
public Stream InputStream { get; } 

// Summary: 
// Saves the contents of an uploaded file. 
// 
// Parameters: 
// filename: 
// The name of the saved file. 
// 
// Exceptions: 
// System.Web.HttpException: 
// The System.Web.Configuration.HttpRuntimeSection.RequireRootedSaveAsPath property 
// of the System.Web.Configuration.HttpRuntimeSection object is set to true, 
// but filename is not an absolute path. 
public void SaveAs(string filename); 
} 

4 个答案:

答案 0 :(得分:0)

FileInfo类和文件内容之间存在差异。您可以使用StreamReader方法通过FileInfo.OpenText访问文件的内容。

var fileInfo = directory.GetFiles("myPattern")
                        .OrderByDescending(f => f.LastWriteTime)
                        .First();
using (StreamReader sr = fileInfo.OpenText()) {
    String s = sr.ReadToEnd();
}

答案 1 :(得分:0)

假设您正在阅读文本文件

  String text = File.ReadAllText(Directory.GetFiles("myPattern").OrderByDescending(f => File.GetLastAccessTime(f)).First());

答案 2 :(得分:0)

FilepathFileInfo对象,您无法将其设置为HttpPostedFile

FileInfo file =    directory.GetFiles("myPattern").OrderByDescending(f => f.LastWriteTime).First();
if (file != null)
   string contents = File.ReadAllText(file.FullName);

答案 3 :(得分:-1)

我通过以下代码获得了所需的解决方案:

  

var myFile = Directory.GetFiles("。")。OrderByDescending(f =>   F).FirstOrDefault();