我目前正在构建一个发送文件的 Web 服务,这也从正在发送的文件中获取 mime 类型,但由于某种原因,我的应用程序看不到文件,更不用说打开了。
我的路径是
file:\\C:\\Users\\Martin\\Documents\\Visual Studio 2010\\Projects\\HTML5Streamer\\
Debug\\Player\\player.html
(这是由我的应用程序创建的。当我在本地使用 Chrome 并粘贴该地址时,我的应用程序被编译到该路径中的调试文件夹,它可以正常工作,chrome 可以查看和访问该文件,
我的 VS 以管理员身份运行,因此应用程序编译也以管理员身份运行,为什么它会获得正确的路径,然后File.Exists()
说它不存在
public string getMimeFromFile(string filename)
{
if (!File.Exists(filename))
throw new FileNotFoundException(filename + " not found"); // this is thrown
byte[] buffer = new byte[256];
using (FileStream fs = new FileStream(filename, FileMode.Open))
{
if (fs.Length >= 256)
fs.Read(buffer, 0, 256);
else
fs.Read(buffer, 0, (int)fs.Length);
}
try
{
System.UInt32 mimetype;
FindMimeFromData(0, null, buffer, 256, null, 0, out mimetype, 0);
System.IntPtr mimeTypePtr = new IntPtr(mimetype);
string mime = Marshal.PtrToStringUni(mimeTypePtr);
Marshal.FreeCoTaskMem(mimeTypePtr);
return mime;
}
catch (Exception e)
{
return "unknown/unknown";
}
}
调用它的方法是
private void ProccessPlayerRequest(HttpListenerContext context)
{
Uri content_uri = context.Request.Url;
string filePath = ApplicationPath + content_uri.AbsolutePath.Replace('/', '\\');
//ApplicationPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
string mimeType = getMimeFromFile(filePath);
context.Response.Headers.Add("Content-Type: " + mimeType);
streamFileToBrowser(filePath, context);
}
使用string filePath = Path.Combine(ApplicationPath, @"Player\player.html");
生产时
"file:\\C:\\Users\\Martin\\Documents\\Visual Studio 2010\\Projects\\HTML5Streamer\\Debug\\Player\\player.html"
是的 file:\ 是从 .Net Framework 中获得的
string ApplicationPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
Service serv = new Service(ApplicationPath);
发送到构造函数的这个应用程序路径是所有正确调用给出的,所以请不要说它不应该有 file:\,因为这是由 .Net Framework 给出的