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

Posted on 2006-04-28
Medium Priority
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

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

Expert Comment

ID: 16567655
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

ID: 16579375
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

Agarici earned 1500 total points
ID: 16585325
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

ID: 16589619
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

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Summary: Persistence is the capability of an application to store the state of objects and recover it when necessary. This article compares the two common types of serialization in aspects of data access, readability, and runtime cost. A ready-to…
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
this video summaries big data hadoop online training demo (http://onlineitguru.com/big-data-hadoop-online-training-placement.html) , and covers basics in big data hadoop .
With just a little bit of  SQL and VBA, many doors open to cool things like synchronize a list box to display data relevant to other information on a form.  If you have never written code or looked at an SQL statement before, no problem! ...  give i…
Suggested Courses

862 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