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

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?
Who is Participating?
AgariciConnect With a Mentor Commented:
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

You can use the Systen.IO. class normally, just supply the appropriate UNC path for the directory.
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
FastEddie___Author Commented:
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)

FastEddie___Author Commented:
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.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.