Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Getting File Path

Getting File Path

Scheduled Pinned Locked Moved C#
questiondatabasesysadmindata-structureshelp
16 Posts 6 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • A ASPnoob

    Hi all, I'm trying to create an app that lets people upload their resume to my database. I've seen tutorials for doing this and they all say the same thing. Number 1 save the original name and file type of the file to be uploaded and convert the file to byte array. Number 2 upload to database. However there is a problem, they all seem to assume one thing and that is, they assume the path of the file to be uploaded is known. Just to show you what I'm talking about below is one of the methods I've found that let you upload a file to the database.

    protected void InsertDoc_Click(object sender, EventArgs e)
    {
    // Read the file and convert it to Byte Array
    string filePath = Server.MapPath("APP_DATA/TestDoc.docx");
    string filename = Path.GetFileName(filePath);

        FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
        BinaryReader br = new BinaryReader(fs);
        Byte\[\] bytes = br.ReadBytes((Int32)fs.Length);
        br.Close();
        fs.Close();
    
        //insert the file into database
        string strQuery = "insert into tblFiles(Name, ContentType, Data) values (@Name, @ContentType, @Data)";
        SqlCommand cmd = new SqlCommand(strQuery);
        cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = filename;
        cmd.Parameters.Add("@ContentType", SqlDbType.VarChar).Value = "application/vnd.ms-word";
        cmd.Parameters.Add("@Data", SqlDbType.Binary).Value = bytes;
        InsertUpdateData(cmd);
    }
    

    The line

    string filePath = Server.MapPath("APP_DATA/TestDoc.docx");

    is supposed to give you the file path but it assumes you already know what it is. I tried to get around this problem by using a FileUpload control and use fileupload1.PostedFile.FileName, but it only returns the file name and extension, not the full path. I have also tried Path.GetFileName( fileupload1.FileName) with no luck. How do I get around this problem? Thanks in advance for replying.

    OriginalGriffO Offline
    OriginalGriffO Offline
    OriginalGriff
    wrote on last edited by
    #5

    File upload controls don'#t give you any path information (because the device originating the file may not support paths, and the path to the original file would give you information about the client machine - which is not allowed for security reasons). But that's ok, - you don't need it. You need the file name and extension - which all upload controls will give you - and you need the file content as a byte stream - which all upload controls will also give you. You don't need to read it any further to get the data you need, since you can't specific the destination location when any user uploads it anyway! This is the method I use: it's probably a bit overkill for you since it handles versioning as well, but...

    /// <summary>
    /// Save an upload into the database.
    /// </summary>
    /// <param name="fl">Control containing the download.</param>
    /// <returns>Status as a string</returns>
    private string SaveUpload(FileUpload fl)
    {
    if (fl.HasFile)
    {
    try
    {
    int version = 0;
    string filename = Path.GetFileName(fl.FileName);
    byte[] filedata = fl.FileBytes;
    string strCon = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["DownloadDatabase"].ConnectionString;
    using (SqlConnection con = new SqlConnection(strCon))
    {
    con.Open();
    // Check version - if the file exists in the DB already, then increase version number.
    using (SqlCommand ver = new SqlCommand("SELECT MAX(version) FROM dlContent WHERE fileName=@FN", con))
    {
    ver.Parameters.AddWithValue("@FN", filename);
    object o = ver.ExecuteScalar();
    if (o != null && o != System.DBNull.Value)
    {
    // Exists already.
    version = (int) o + 1;
    }
    }
    // Stick file into database.
    using (SqlCommand ins = new SqlCommand("INSERT INTO dlContent (iD, fileName, description, dataContent, version, uploadedOn) " +
    "VALUES (@ID, @FN, @DS, @DT, @VS, @UD)", con))
    {
    ins.Parameters.AddWithValue("@ID", Guid.NewGuid());
    ins.Parameters.AddWith

    "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
    "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

    A P 2 Replies Last reply
    0
    • OriginalGriffO OriginalGriff

      File upload controls don'#t give you any path information (because the device originating the file may not support paths, and the path to the original file would give you information about the client machine - which is not allowed for security reasons). But that's ok, - you don't need it. You need the file name and extension - which all upload controls will give you - and you need the file content as a byte stream - which all upload controls will also give you. You don't need to read it any further to get the data you need, since you can't specific the destination location when any user uploads it anyway! This is the method I use: it's probably a bit overkill for you since it handles versioning as well, but...

      /// <summary>
      /// Save an upload into the database.
      /// </summary>
      /// <param name="fl">Control containing the download.</param>
      /// <returns>Status as a string</returns>
      private string SaveUpload(FileUpload fl)
      {
      if (fl.HasFile)
      {
      try
      {
      int version = 0;
      string filename = Path.GetFileName(fl.FileName);
      byte[] filedata = fl.FileBytes;
      string strCon = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["DownloadDatabase"].ConnectionString;
      using (SqlConnection con = new SqlConnection(strCon))
      {
      con.Open();
      // Check version - if the file exists in the DB already, then increase version number.
      using (SqlCommand ver = new SqlCommand("SELECT MAX(version) FROM dlContent WHERE fileName=@FN", con))
      {
      ver.Parameters.AddWithValue("@FN", filename);
      object o = ver.ExecuteScalar();
      if (o != null && o != System.DBNull.Value)
      {
      // Exists already.
      version = (int) o + 1;
      }
      }
      // Stick file into database.
      using (SqlCommand ins = new SqlCommand("INSERT INTO dlContent (iD, fileName, description, dataContent, version, uploadedOn) " +
      "VALUES (@ID, @FN, @DS, @DT, @VS, @UD)", con))
      {
      ins.Parameters.AddWithValue("@ID", Guid.NewGuid());
      ins.Parameters.AddWith

      A Offline
      A Offline
      ASPnoob
      wrote on last edited by
      #6

      Thank you so much for replying. Can you please do me one more favor, can you show me how to retrieve the file after it is stored and display it in the browser. None of the tutorials I'm I've looked at worked, I did not get any errors using the code from the tutorials, they just don't do anything. I've been at this for days and I really need to know how to retrieve and display a word doc in the browser as soon as possible. Thanks again for your help.

      OriginalGriffO E 2 Replies Last reply
      0
      • A ASPnoob

        Thank you so much for replying. Can you please do me one more favor, can you show me how to retrieve the file after it is stored and display it in the browser. None of the tutorials I'm I've looked at worked, I did not get any errors using the code from the tutorials, they just don't do anything. I've been at this for days and I really need to know how to retrieve and display a word doc in the browser as soon as possible. Thanks again for your help.

        OriginalGriffO Offline
        OriginalGriffO Offline
        OriginalGriff
        wrote on last edited by
        #7

        The basic answer is: "You can't" The problem is that this is a Word Document - so there is no native browser support for viewing it, it requires either the appropriate version of Word, or a document converter. Think about it from a user POV: Browse to your site, press button marked "open CV". In order to view a Word document directly, it must download to his computer (not a problem, easy to do) then open Word and load the file automatically. Here we have the problem: 1) You cannot run an application of any sort directly on his computer because the antivirus will not let you (well, you can in some cases, but it's not a good idea to rely on it, as it requires Windows, IE and ActiveX support, none of which you can rely on). 2) If you can get round (1), you need to force the browser to open the file - which you can't do, again except in specific circumstances, which do not apply to most people. Again, anti virus is going to do it's best to stop you! 3) If you can get round (1) and (2), then you have a problem in that you can't guarantee that Word is loaded on all browser equipped equipment (heck, it isn't even loaded on all PCs!) so you still can't be sure that anyone can read it. 4) If you get round (1), (2) and (3) - and that is a very big "if" - then you have the problem of making sure that the Word file can be read by the version of Word on the Client! A better approach is to store the DOC / DOCX file and allow downloads, so the user can print / save / share it as necessary, but for viewing either convert it to HTML (which can be shown directly) or an image format (which can again be shown directly). You could (probably, I haven't tried) do both by installing Word on the server, and using Office Interop to load and save the data, or by using a file converter on the server.

        Ideological Purity is no substitute for being able to stick your thumb down a pipe to stop the water

        "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
        "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

        1 Reply Last reply
        0
        • A ASPnoob

          Thank you so much for replying. Can you please do me one more favor, can you show me how to retrieve the file after it is stored and display it in the browser. None of the tutorials I'm I've looked at worked, I did not get any errors using the code from the tutorials, they just don't do anything. I've been at this for days and I really need to know how to retrieve and display a word doc in the browser as soon as possible. Thanks again for your help.

          E Offline
          E Offline
          Ed Hill _5_
          wrote on last edited by
          #8

          One option that may work for you, there is a microsoft tool that converts documents into .docx format, can you run this on the server that the files are uploaded to. If this is an option and you can get it implemented there are serveral projects out there on the interwebs that show you how to convert a docx file into html, this allows it to be viewed in a browser. I'm not at my work PC at the moment but i have a smaple project on there that allows demonstrates docx files viewed in a web browser.

          1 Reply Last reply
          0
          • OriginalGriffO OriginalGriff

            File upload controls don'#t give you any path information (because the device originating the file may not support paths, and the path to the original file would give you information about the client machine - which is not allowed for security reasons). But that's ok, - you don't need it. You need the file name and extension - which all upload controls will give you - and you need the file content as a byte stream - which all upload controls will also give you. You don't need to read it any further to get the data you need, since you can't specific the destination location when any user uploads it anyway! This is the method I use: it's probably a bit overkill for you since it handles versioning as well, but...

            /// <summary>
            /// Save an upload into the database.
            /// </summary>
            /// <param name="fl">Control containing the download.</param>
            /// <returns>Status as a string</returns>
            private string SaveUpload(FileUpload fl)
            {
            if (fl.HasFile)
            {
            try
            {
            int version = 0;
            string filename = Path.GetFileName(fl.FileName);
            byte[] filedata = fl.FileBytes;
            string strCon = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["DownloadDatabase"].ConnectionString;
            using (SqlConnection con = new SqlConnection(strCon))
            {
            con.Open();
            // Check version - if the file exists in the DB already, then increase version number.
            using (SqlCommand ver = new SqlCommand("SELECT MAX(version) FROM dlContent WHERE fileName=@FN", con))
            {
            ver.Parameters.AddWithValue("@FN", filename);
            object o = ver.ExecuteScalar();
            if (o != null && o != System.DBNull.Value)
            {
            // Exists already.
            version = (int) o + 1;
            }
            }
            // Stick file into database.
            using (SqlCommand ins = new SqlCommand("INSERT INTO dlContent (iD, fileName, description, dataContent, version, uploadedOn) " +
            "VALUES (@ID, @FN, @DS, @DT, @VS, @UD)", con))
            {
            ins.Parameters.AddWithValue("@ID", Guid.NewGuid());
            ins.Parameters.AddWith

            P Offline
            P Offline
            Pete OHanlon
            wrote on last edited by
            #9

            I'm afraid you have a race condition in your code. Suppose two files with the same name are being uploaded at the same time. Both could hit the version retrieval code at the same time, which will result in them both getting the same version number. The reason is because there is a delay between the get version and the update part of the code.

            *pre-emptive celebratory nipple tassle jiggle* - Sean Ewington

            "Mind bleach! Send me mind bleach!" - Nagy Vilmos

            CodeStash - Online Snippet Management | My blog | MoXAML PowerToys | Mole 2010 - debugging made easier

            OriginalGriffO 1 Reply Last reply
            0
            • P Pete OHanlon

              I'm afraid you have a race condition in your code. Suppose two files with the same name are being uploaded at the same time. Both could hit the version retrieval code at the same time, which will result in them both getting the same version number. The reason is because there is a delay between the get version and the update part of the code.

              *pre-emptive celebratory nipple tassle jiggle* - Sean Ewington

              "Mind bleach! Send me mind bleach!" - Nagy Vilmos

              CodeStash - Online Snippet Management | My blog | MoXAML PowerToys | Mole 2010 - debugging made easier

              OriginalGriffO Offline
              OriginalGriffO Offline
              OriginalGriff
              wrote on last edited by
              #10

              :-O i did write it a long time ago... Oops! In the field where it is being used it is very unlikely to happen (because the file names are specific to the customer site), but you are absolutely right - I'll fix it in the code next time I release an update - a quick stored proc will fix that! Thanks for the head up...:thumbsup:

              Ideological Purity is no substitute for being able to stick your thumb down a pipe to stop the water

              "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
              "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

              P 1 Reply Last reply
              0
              • OriginalGriffO OriginalGriff

                :-O i did write it a long time ago... Oops! In the field where it is being used it is very unlikely to happen (because the file names are specific to the customer site), but you are absolutely right - I'll fix it in the code next time I release an update - a quick stored proc will fix that! Thanks for the head up...:thumbsup:

                Ideological Purity is no substitute for being able to stick your thumb down a pipe to stop the water

                P Offline
                P Offline
                Pete OHanlon
                wrote on last edited by
                #11

                No problem. I'm glad I can help.

                *pre-emptive celebratory nipple tassle jiggle* - Sean Ewington

                "Mind bleach! Send me mind bleach!" - Nagy Vilmos

                CodeStash - Online Snippet Management | My blog | MoXAML PowerToys | Mole 2010 - debugging made easier

                1 Reply Last reply
                0
                • A ASPnoob

                  Hi all, I'm trying to create an app that lets people upload their resume to my database. I've seen tutorials for doing this and they all say the same thing. Number 1 save the original name and file type of the file to be uploaded and convert the file to byte array. Number 2 upload to database. However there is a problem, they all seem to assume one thing and that is, they assume the path of the file to be uploaded is known. Just to show you what I'm talking about below is one of the methods I've found that let you upload a file to the database.

                  protected void InsertDoc_Click(object sender, EventArgs e)
                  {
                  // Read the file and convert it to Byte Array
                  string filePath = Server.MapPath("APP_DATA/TestDoc.docx");
                  string filename = Path.GetFileName(filePath);

                      FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                      BinaryReader br = new BinaryReader(fs);
                      Byte\[\] bytes = br.ReadBytes((Int32)fs.Length);
                      br.Close();
                      fs.Close();
                  
                      //insert the file into database
                      string strQuery = "insert into tblFiles(Name, ContentType, Data) values (@Name, @ContentType, @Data)";
                      SqlCommand cmd = new SqlCommand(strQuery);
                      cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = filename;
                      cmd.Parameters.Add("@ContentType", SqlDbType.VarChar).Value = "application/vnd.ms-word";
                      cmd.Parameters.Add("@Data", SqlDbType.Binary).Value = bytes;
                      InsertUpdateData(cmd);
                  }
                  

                  The line

                  string filePath = Server.MapPath("APP_DATA/TestDoc.docx");

                  is supposed to give you the file path but it assumes you already know what it is. I tried to get around this problem by using a FileUpload control and use fileupload1.PostedFile.FileName, but it only returns the file name and extension, not the full path. I have also tried Path.GetFileName( fileupload1.FileName) with no luck. How do I get around this problem? Thanks in advance for replying.

                  P Offline
                  P Offline
                  Pete OHanlon
                  wrote on last edited by
                  #12

                  When I do this, to avoid clashes of file and, I just use a guid as the file name on the disk. Simply store the original file name in your database along with the new name.

                  *pre-emptive celebratory nipple tassle jiggle* - Sean Ewington

                  "Mind bleach! Send me mind bleach!" - Nagy Vilmos

                  CodeStash - Online Snippet Management | My blog | MoXAML PowerToys | Mole 2010 - debugging made easier

                  L 1 Reply Last reply
                  0
                  • P Pete OHanlon

                    When I do this, to avoid clashes of file and, I just use a guid as the file name on the disk. Simply store the original file name in your database along with the new name.

                    *pre-emptive celebratory nipple tassle jiggle* - Sean Ewington

                    "Mind bleach! Send me mind bleach!" - Nagy Vilmos

                    CodeStash - Online Snippet Management | My blog | MoXAML PowerToys | Mole 2010 - debugging made easier

                    L Offline
                    L Offline
                    Lost User
                    wrote on last edited by
                    #13

                    Pete O'Hanlon wrote:

                    I just use a guid as the file name on the disk

                    I read that as quid and thought :wtf: . :doh:

                    One of these days I'm going to think of a really clever signature.

                    P 1 Reply Last reply
                    0
                    • L Lost User

                      Pete O'Hanlon wrote:

                      I just use a guid as the file name on the disk

                      I read that as quid and thought :wtf: . :doh:

                      One of these days I'm going to think of a really clever signature.

                      P Offline
                      P Offline
                      Pete OHanlon
                      wrote on last edited by
                      #14

                      That's because you're obsessed with money. ;P

                      *pre-emptive celebratory nipple tassle jiggle* - Sean Ewington

                      "Mind bleach! Send me mind bleach!" - Nagy Vilmos

                      CodeStash - Online Snippet Management | My blog | MoXAML PowerToys | Mole 2010 - debugging made easier

                      L 1 Reply Last reply
                      0
                      • P Pete OHanlon

                        That's because you're obsessed with money. ;P

                        *pre-emptive celebratory nipple tassle jiggle* - Sean Ewington

                        "Mind bleach! Send me mind bleach!" - Nagy Vilmos

                        CodeStash - Online Snippet Management | My blog | MoXAML PowerToys | Mole 2010 - debugging made easier

                        L Offline
                        L Offline
                        Lost User
                        wrote on last edited by
                        #15

                        No, it's because both my eyes and brain are getting more feeble. :(

                        One of these days I'm going to think of a really clever signature.

                        P 1 Reply Last reply
                        0
                        • L Lost User

                          No, it's because both my eyes and brain are getting more feeble. :(

                          One of these days I'm going to think of a really clever signature.

                          P Offline
                          P Offline
                          Pete OHanlon
                          wrote on last edited by
                          #16

                          Richard MacCutchan wrote:

                          No, it's because both my eyes and brain are getting more feeble

                          The brain part isn't an issue for me - mine was always feeble. The eyes are rapidly catching up.

                          *pre-emptive celebratory nipple tassle jiggle* - Sean Ewington

                          "Mind bleach! Send me mind bleach!" - Nagy Vilmos

                          CodeStash - Online Snippet Management | My blog | MoXAML PowerToys | Mole 2010 - debugging made easier

                          1 Reply Last reply
                          0
                          Reply
                          • Reply as topic
                          Log in to reply
                          • Oldest to Newest
                          • Newest to Oldest
                          • Most Votes


                          • Login

                          • Don't have an account? Register

                          • Login or register to search.
                          • First post
                            Last post
                          0
                          • Categories
                          • Recent
                          • Tags
                          • Popular
                          • World
                          • Users
                          • Groups