为什么我的应用程序无法打开存在的文件?

时间:2012-05-07 19:57:26

标签: c# web-services

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

string ApplicationPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
            Service serv = new Service(ApplicationPath);

发送到构造函数的这个应用程序路径是从所有正确的调用中得到的,所以请不要说它不应该有文件:\,因为它是由.Net Framework提供的

2 个答案:

答案 0 :(得分:2)

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

修改:在Application.ExecutablePath来电中尝试使用Path.GetDirectoryName()代替CodeBase参考。您可能必须添加对程序集System.Windows.Forms的引用。

string ApplicationPath = System.IO.Path.GetDirectoryName(Application.ExecutablePath);

<强> EDIT2:

您也可以使用(取自我的dll):

public static FileInfo Application()
{
    return new FileInfo(Environment.GetCommandLineArgs()[0]);
}

然后:

string ApplicationPath = Application().DirectoryName;

答案 1 :(得分:0)

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

相关问题