How to provide user name and password when connecting to a network share

后端 未结 11 1684
不知归路
不知归路 2020-11-22 00:34

When connecting to a network share for which the current user (in my case, a network enabled service user) has no rights, name and password have to be provided.

I kn

11条回答
  •  天涯浪人
    2020-11-22 01:24

    I searched lots of methods and i did it my own way. You have to open a connection between two machine via command prompt NET USE command and after finishing your work clear the connection with command prompt NET USE "myconnection" /delete.

    You must use Command Prompt process from code behind like this:

    var savePath = @"\\servername\foldername\myfilename.jpg";
    var filePath = @"C:\\temp\myfileTosave.jpg";
    

    Usage is simple:

    SaveACopyfileToServer(filePath, savePath);
    

    Here is functions:

    using System.IO
    using System.Diagnostics;
    
    
    public static void SaveACopyfileToServer(string filePath, string savePath)
        {
            var directory = Path.GetDirectoryName(savePath).Trim();
            var username = "loginusername";
            var password = "loginpassword";
            var filenameToSave = Path.GetFileName(savePath);
    
            if (!directory.EndsWith("\\"))
                filenameToSave = "\\" + filenameToSave;
    
            var command = "NET USE " + directory + " /delete";
            ExecuteCommand(command, 5000);
    
            command = "NET USE " + directory + " /user:" + username + " " + password;
            ExecuteCommand(command, 5000);
    
            command = " copy \"" + filePath + "\"  \"" + directory + filenameToSave + "\"";
    
            ExecuteCommand(command, 5000);
    
    
            command = "NET USE " + directory + " /delete";
            ExecuteCommand(command, 5000);
        }
    

    And also ExecuteCommand function is:

    public static int ExecuteCommand(string command, int timeout)
        {
            var processInfo = new ProcessStartInfo("cmd.exe", "/C " + command)
                                  {
                                      CreateNoWindow = true, 
                                      UseShellExecute = false, 
                                      WorkingDirectory = "C:\\",
                                  };
    
            var process = Process.Start(processInfo);
            process.WaitForExit(timeout);
            var exitCode = process.ExitCode;
            process.Close();
            return exitCode;
        } 
    

    This functions worked very fast and stable for me.

提交回复
热议问题