在网络共享位置创建文本文件

问题描述:





我有一个网络共享驱动器(\\\\\\\,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,一些记录。我可以使用特定用户(user/pass)访问驱动器路径。如何使用C#访问共享位置并创建文本文件?





Hi,

I have a network shared drive ("\\serverIP\folder") on which I would want to create text file and add some records. I can access on the drive path with a specific user ("user"/"pass"). How can I access the shared location and create text file using C#?


 string filePath = "\\\\10.1.2.179\\source\\";
                StreamWriter SW1;
FileIOPermission myPerm = new FileIOPermission(FileIOPermissionAccess.AllAccess,FillePath+fileName);
                myPerm.Assert();
                SW1 = File.CreateText(filePath+fileName);







谢谢,




Thanks,

您可以模拟该用户创建文件。查看下面的博文。

模拟代码C# [ ^ ]



我从该博客帖子中复制了代码,

you can impersonate that user for creating the file. check below blog post.
impersonation code C#[^]

I have copied code from that blog post,
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Security.Principal;
 
public class ImpersonatedUser : IDisposable
{
    IntPtr userHandle;
    WindowsImpersonationContext impersonationContext;
 
    public ImpersonatedUser(string user, string domain, string password)
    {
        userHandle = IntPtr.Zero;
        bool loggedOn = LogonUser(
            user,
            domain,
            password,
            LogonType.Interactive,
            LogonProvider.Default,
            out userHandle);
 
        if (!loggedOn)
            throw new Win32Exception(Marshal.GetLastWin32Error());
 
        // Begin impersonating the user
        impersonationContext = WindowsIdentity.Impersonate(userHandle);
    }
 
    public void Dispose()
    {
        if (userHandle != IntPtr.Zero)
        {
            CloseHandle(userHandle);
            userHandle = IntPtr.Zero;
            impersonationContext.Undo();
        }
    } 
 
    [DllImport("advapi32.dll", SetLastError = true)]
    static extern bool LogonUser(
        string lpszUsername,
        string lpszDomain,
        string lpszPassword,
        LogonType dwLogonType,
        LogonProvider dwLogonProvider,
        out IntPtr phToken
        );
 
    [DllImport("kernel32.dll", SetLastError = true)]
    static extern bool CloseHandle(IntPtr hHandle);
 
    enum LogonType : int
    {
        Interactive = 2,
        Network = 3,
        Batch = 4,
        Service = 5,
        NetworkCleartext = 8,
        NewCredentials = 9,
    }
 
    enum LogonProvider : int
    {
        Default = 0,
    }
}





将以上课程添加到您的项目中并执行以下操作





add above class to your project and do as below

using (var impersonation = new ImpersonatedUser(username, domain, password))
{
    string filePath = "\\\\10.1.2.179\\source\\";
    StreamWriter SW1;
    FileIOPermission myPerm = new FileIOPermission(FileIOPermissionAccess.AllAccess,FillePath+fileName);
    myPerm.Assert();
    SW1 = File.CreateText(filePath+fileName);
}



如果你想了解更多关于冒充阅读下面的文章

C#.NET中的完整模拟演示 [ ^ ]