How to access a network directory programatically with C# from a web app.

Posted on 2006-04-28
Last Modified: 2008-01-09
I have a C# web app that needs the ability to access a directory on our company network so I can place a pdf file there.

Does anybody know the steps involved in accessing a network directory?
Question by:FastEddie___
    LVL 10

    Expert Comment

    You can use the Systen.IO. class normally, just supply the appropriate UNC path for the directory.
    LVL 10

    Expert Comment

    try this link also.

    you can access the network share by System.IO Classes. if u need authentication try this link also



    using System;
    using System.Management;
    using System.IO;

    static void Main(string[] args)
            }//end main

            static void UploadStuff()
                using (StreamWriter sw = new StreamWriter("\\\\lsib\\ecs$\\Josh\\TestFile.txt"))
                    // Add some text to the file.
                    sw.WriteLine("I am writing in the file");
                    sw.WriteLine("The date is: " + DateTime.Now);
            }//end UploadStuff()

            static void MapDriveECS()
                String myUser = "mydomain\\mydomainuser";
                String myPass = "mydomainuserpassword";
                String cmdString = "net use \\\\lsib\\ecs$ /user:" + myUser + " " +myPass;
                ManagementClass processClass = new ManagementClass("Win32_Process");
                object[] methodArgs = { cmdString, null, null, 0 };
                object result = processClass.InvokeMethod("Create", methodArgs);

                Console.WriteLine("Creation of process returned: " + result);
                Console.WriteLine("Process ID: {0}", methodArgs[3]);
            }//end MapDrive method

    Author Comment

    Hi prakash_prk,

    Thanks for the input but C# does not have a System.Management namespace.

    I tried using the UNC Pathe but that is what is not working.

    I have also tried setting ASP.NET user permissions on the destination folder to full permissions but it still didn't work.

    I can confirm that putting the pdf file in the local web server directory  "C:\\export\\" works just fine. I am building the pdf and it is
    being placed in the web server's C:  However, when I try to place the PDF in a different network location, for example:
    "Ecab2\\UEPDF\\Export\\"  I get an access denied error. The best results that I have gotten is when I use the path:
    "Kcook\\C\\Export\\" I get this message inside the crystal reports viewer page"

    "Error in File C:\DOCUME~1\PROGRA~\ASPNET\LOCALS~1\Temp\temp_cbb010a6-5bd4-4183-aObb-e04ff62e9a9c.rpt:
    Access to report file denied. Another program may be using it."

    The fact that the crystal report is being built is a good sign but the pdf file is not being put inside Kcook's Export directory.

    Here is the code that I'm using:


    using CrystalDecisions.CrystalReports.Engine;
    using CrystalDecisions.Shared;
    using System.Data.SqlClient;
    using System;
    using System.Collections;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Web;
    using System.Web.SessionState;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.HtmlControls;
    using System.Configuration;
    using System.IO;

    namespace MLS
          /// <summary>
          /// Summary description for dspNeighborhoodCR.
          /// </summary>
          public class dspNeighborhoodCR : System.Web.UI.Page

                //CR Variable
                rptNeighborhood crReportDocument;

                // EXPORT CR Variables                    
                ExportOptions crExportOptions;
                DiskFileDestinationOptions crDiskFileDestinationOptions;
                protected System.Web.UI.WebControls.Button cmdExportPDF;

                protected CrystalDecisions.Web.CrystalReportViewer CrystalReportViewer1;
                private void Page_Load(object sender, System.EventArgs e)
                      CrystalReportViewer1.Visible = true;

                      string CONN = ConfigurationSettings.AppSettings["DB_CONN"];
                      SqlConnection connObj = new SqlConnection(CONN);
                      SqlCommand cmdObj = new SqlCommand("MLS_Neighborhood", connObj);
                      cmdObj.CommandType = CommandType.StoredProcedure;
                      SqlDataAdapter da = new SqlDataAdapter ( cmdObj ) ;
                      DataSet dataSet = new DataSet();
                      da.SelectCommand.CommandTimeout = 0;
                      da.Fill(dataSet, "MLS");
                      crReportDocument = new rptNeighborhood();
                      CrystalReportViewer1.ReportSource = crReportDocument;
                      // ****************************************************
                      //   start export report of pdf to local file system
                      // ****************************************************
                      //Check to see if the application directory has a subdirectory called "Exported".
                      //If not, create the directory since exported files will be placed here.
                      //This uses the Directory class of the System.IO namespace.
                      string ExportPath;
                      ExportPath = ConfigurationSettings.AppSettings["PAPERWISE_PATH"];
                      if (Directory.Exists(ExportPath) == false) Directory.CreateDirectory(ExportPath);

                      // First we must create a new instance of the diskfiledestinationoptions class and
                      // set variable called crExportOptions to the exportoptions class of the reportdocument.
                      crDiskFileDestinationOptions = new DiskFileDestinationOptions();
                      crExportOptions = crReportDocument.ExportOptions;
                      //Export to PDF

                      //append a filename to the export path and set this file as the filename property for
                      //the DestinationOptions class
                      string today = DateTime.Now.ToString("MMMMddyyyy_HHmm");
                      string fullFileName = ExportPath+today+"_NeighborhoodReport.pdf";
                      crDiskFileDestinationOptions.DiskFileName = fullFileName ;

                      //set the required report ExportOptions properties
                      crExportOptions.DestinationOptions = crDiskFileDestinationOptions;
                      crExportOptions.ExportDestinationType = ExportDestinationType.DiskFile;
                      crExportOptions.ExportFormatType = ExportFormatType.PortableDocFormat;


                      //Once the export options have been set for the report, the report can be exported.
                      //The Export command does not take any arguments
                            // Export the report
                            crReportDocument.Export();  // **** this is where it fails. *****

                      catch (Exception err)

                      // ****************************************************
                      //  end export report of pdf to local file system
                      // ****************************************************

                #region Web Form Designer generated code
                override protected void OnInit(EventArgs e)
                      // CODEGEN: This call is required by the ASP.NET Web Form Designer.
                /// <summary>
                /// Required method for Designer support - do not modify
                /// the contents of this method with the code editor.
                /// </summary>
                private void InitializeComponent()
                      this.Load += new System.EventHandler(this.Page_Load);


                private void ExportToPDF_Engage(object sender, System.EventArgs e)

    LVL 11

    Accepted Solution

    maybe your app is runing under some credentials that do not have access to that network folder.
    try to impersonate a user that you know has access to that resource, do the copy, then revert the identity


    Author Comment

    Agarici was right on.

    I had to create a new network user on the server where the pdf was being sent to, then
    I had to set impersonate to "true" and give the new users name and password.

    Thanks to everyone for your input.

    Featured Post

    Threat Intelligence Starter Resources

    Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

    Join & Write a Comment

    We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
    Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
    To add imagery to an HTML email signature, you have two options available to you. You can either add a logo/image by embedding it directly into the signature or hosting it externally and linking to it. The vast majority of email clients display l…
    how to add IIS SMTP to handle application/Scanner relays into office 365.

    729 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    19 Experts available now in Live!

    Get 1:1 Help Now