views:

119

answers:

2

i want to ask how to open specific file (the file out of the server, i have a relative path to it stored in config file) with its application when click on specific link button or hyper link...

like ::

open .docx with word.

or .pdf with acrobat reader

i tried several methods but , i get different errors like

"Cannot use a leading .. to exit above the top directory"

this my code::

public void ProcessRequest(HttpContext context) {

            int newsId = int.Parse(context.Session["newsId"].ToString());
            int FK_UnitId = int.Parse(context.Session["UserData"].ToString());
            string dirPathForTextFiles = ConfigurationManager.AppSettings.GetValues("ThePath").First() + "/" + "NewsTextFiles" + "/" + "UnitNum" + FK_UnitId.ToString() + "_" + "NewsNum" + newsId + "/";
            DataTable UpdatedDateTable = (DataTable)context.Session["theLastUpdatedTextFile"];
            UpdatedDateTable.AcceptChanges();
            context.Session.Add("currentTextFile", UpdatedDateTable);
            List<string> l = new List<string>(UpdatedDateTable.Rows.Count);

            try
            {

                l.Add(dirPathForTextFiles + UpdatedDateTable.Rows[0]["fileName"].ToString());
                context.Response.ContentType = getContentType(dirPathForTextFiles + UpdatedDateTable.Rows[0]["fileName"].ToString());
                System.Diagnostics.Process.Start(l[0]);         
                context.ClearError();

            }
            catch (IOException e)
            {
                string message = e.Message;
            }


    }

    string getContentType(String path)
    {
        switch (Path.GetExtension(path))
        {
            case ".doc": return "   application/msword";
            case ".docx": return "application/msword";
            case ".pdf": return "application/pdf";

            default: break;
        }
        return "";
    }`
+3  A: 

In order to get the full file path on the server you'll want to use Server.MapPath.

string fullFileName = Server.MapPath("../myFile.pdf");

Edit: After that you'll need the Process object to "run" it:

System.Diagnostics.Process.Start(fullFileName);

Edit 2: If you want the file to be opened on the client side, your best bet is to create and HTTP Handler and set the appropriate mime type on your response before streaming it out from your handler.

Edit 3: Code to stream a file out to client.

public void ProcessRequest(HttpContext context)  
{   
   int newsId = int.Parse(context.Session["newsId"].ToString());
   int FK_UnitId = int.Parse(context.Session["UserData"].ToString());
   string dirPathForTextFiles =  ConfigurationManager.AppSettings.GetValues("ThePath").First() + "/" + "NewsTextFiles" + "/" + "UnitNum" + FK_UnitId.ToString() + "_" + "NewsNum" + newsId + "/";
   DataTable UpdatedDateTable = (DataTable)context.Session["theLastUpdatedTextFile"];
   UpdatedDateTable.AcceptChanges();
   context.Session.Add("currentTextFile", UpdatedDateTable);
   List<string> l = new List<string>(UpdatedDateTable.Rows.Count);

   try
   {

      l.Add(dirPathForTextFiles + UpdatedDateTable.Rows[0]["fileName"].ToString());
       context.Response.ContentType = getContentType(dirPathForTextFiles + UpdatedDateTable.Rows[0]["fileName"].ToString());
       using (FileStream fs = new FileStream(l[0], FileMode.Open, FileAccess.Read))
       {
          long chunkSize = fs.Length; 
          byte[] buf = new byte[chunkSize]; 
          int bytesRead = 1; 
          bytesRead = fs.Read(buf, 0,(int)chunkSize); 
          if (bytesRead > 0) context.Response.OutputStream.Write(buf, 0, buf.Length);
          context.Response.OutputStream.Flush();
      }

  }
  catch (IOException e)
  {
     string message = e.Message;
  }   
}
Steve Danner
i know but the file out of my server , i wanna to open this file with its applicaton
I edited as a possible solution, however do you want to open it on the SERVER or do you want the the user to open the file on the CLIENT?
Steve Danner
i wanna the user to open it on the client side
Alright, Edit 2 gives you a start on how to stream a file out to the client. The Mime type is extremely important to allow the users to open the appropriate application client-side.
Steve Danner
yes , i use HTTP handler but what i want is( the code to write to open the file with its application)
i get the following error "The system cannot find the file specified" although the path is correct but it's a relative path
[Win32Exception (0x80004005): The system cannot find the file specified] System.Diagnostics.Process.StartWithShellExecuteEx(ProcessStartInfo startInfo) +909 System.Diagnostics.Process.Start() +131 System.Diagnostics.Process.Start(ProcessStartInfo startInfo) +49 System.Diagnostics.Process.Start(String fileName) +31
Have you used Server.MapPath to translate the relative file path to an absolute file path?
Steve Danner
no because the file out of the server and i use relative path ,and also can't use ../ with this method"Cannot use a leading .. to exit above the top directory."
i edit my question to show the code
It's up to the client's machine what application it uses to run a file it downloads from your server. Writing a server-side command that would cause the client to launch an app would be a pretty enormous security breach. There may be some misunderstanding about the relationship between server- and client-side behavior in this question...
djacobson
then if u think that this will be security breach , what u suggest to fix my problem , simply i wanna when the user click on link button the file opened with the appropriate application (note:the file out of the server)
I agree that there's definitely a big question as to exactly what was originally meant by "open the file in the appropriate application". However, I think I understand now. Eliminate the Process.Start that we've been talking about, that is the security breach djacobson was talking about. I have edited my answer yet again with your code, modified.
Steve Danner
this is great Steave ,but two more things1- please edit the code : byte[] buf = new byte[chunkSize];2- when i click the link button and click open to open the file with its application such as pdf i have the following message:Cannot use Adobe Reader to view to view PDF in your web browser .reader will now exit.please exit your browser and try again
Sorry, I just wrote that code from memory. You may need to call context.Response.OutputStream.Flush() at the end.
Steve Danner
thank u so much Steve , really i appreciate your help , but i still face the same last problem Cannot use Adobe Reader to view to view PDF in your web browser .reader will now exit.please exit your browser and try againand for word documents i can't open the file , must download it then open the file and after download the file i get this message when i try to open it"the file RetreiveTextFile can't be opened because there are problems with the contents" and the details the file is corrupt and can't be opened .. i don't know what 's the problem.
This sounds like an issue with the client-side instance of Adobe.
Steve Danner
but what about word application
i feel the problem is that the files tries to be opened in the browser,not with their application and i don't know why?
and finally , i fixes the problem..when i determine the maximum size by 100000,the file is not read until the end and the message that your file is corrupted is appeared,the solution to this problem is the following modification::`long chunkSize = fs.Length;``byte[] buf = new byte[chunkSize];``int bytesRead = 1;``bytesRead = fs.Read(buf, 0,(int)chunkSize);``if (bytesRead > 0) context.Response.OutputStream.Write(buf, 0, buf.Length);``context.Response.OutputStream.Flush();`
thank u so much Steve for your great help.please edit the last answer.
Excellent! I'm glad you got it working!
Steve Danner
A: 

System.Diagnostics.Process.Start("Start FilePath")

Vivek
i get the following error "The system cannot find the file specified"although the path is correct but it's a relative path
It could be a rights Issue.
Vivek
no i run the visual studio as an adminstrator