0

我目前正在构建一个发送文件的 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 给出的

4

2 回答 2

2

尝试file:\\从文件名的开头删除 。

编辑: 尝试在您的通话中使用Application.ExecutablePath而不是 CodeBase 参考。Path.GetDirectoryName()您可能必须添加对程序集的引用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;
于 2012-05-07T20:01:30.377 回答
0

System.IO.File适用于文件名,而不是 URI,因此file:/无法识别前缀。Chrome 之所以有效,是因为它正在为您将 URI 转换为系统文件名。

于 2012-05-07T20:05:31.683 回答