为什么我的应用程序无法打开存在的文件
本文关键字:存在 文件 我的 应用程序 为什么 | 更新日期: 2023-09-27 18:33:37
我目前正在构建一个发送文件的 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"
是的文件:''是从 .Net 框架中获取的
string ApplicationPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
Service serv = new Service(ApplicationPath);
发送到构造函数的这个应用程序路径是从所有正确的调用中给出的,所以请不要说它不应该有 file:''正如.Net框架给出的那样
尝试从文件名的开头删除file:''
。
编辑:尝试在Path.GetDirectoryName()
调用中使用Application.ExecutablePath
而不是代码库引用。 您可能需要添加对程序集System.Windows.Forms
的引用。
string ApplicationPath = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
编辑2:
你也可以使用(取自我的一个dll):
public static FileInfo Application()
{
return new FileInfo(Environment.GetCommandLineArgs()[0]);
}
然后:
string ApplicationPath = Application().DirectoryName;
System.IO.File
使用文件名,而不是 URI,因此无法识别file:/
前缀。Chrome 之所以有效,是因为它会为您将 URI 转换为系统文件名。