SHARE:

How to read/write files on a network drive?

As an application developer, it is often seen reading / writing files locally or on a server for a web application.
However, in keeping the architecture already in place, sometimes, for safety reasons, that reading directories / write are on another machine, thus it is necessary to create network drives mapped on a particular machine (the machine that executes your program), this article will describe how.

Before accessing to your file in the network drive write this code :

 Process cred = new Process();

 cred.StartInfo.FileName = "net";
 cred.StartInfo.Arguments = @"use \\computername\sharename password /user:username \PERSISTENT:YES";
 cred.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
 cred.Start();
 cred.WaitForExit();

I recommand to use \PERSISTENT:YES , the network connection will be persistent, and won’t be closed after the next logon.

Now you should be able to create files, write (and read) on the network drive, like this :

using (System.IO.FileStream fs = System.IO.File.Create(@"\\computername\sharename\myfile.txt"))
{

}

Written by

anthonygiretti

Anthony is a specialist in Web technologies (14 years of experience), in particular Microsoft .NET and learns the Cloud Azure platform. He has received twice the Microsoft MVP award and he is also certified Microsoft MCSD and Azure Fundamentals.
%d bloggers like this: