.net c# 服务器共享文件夹 windows远程登陆 代码

一个刚刚开始学习编程的人,如果遇到问题无法解决可能会寻找别的解决方案,如果长此以往可能会放弃这门语言而学习其他的语言...

开源与分享的重要性

使用场景:将网站所有附件上传到指定服务器的共享目录下,首先在服务器上新建文件夹并共享 

1. 新建类 FileHelper

namespace Frame.FileHelper
{

public class FileHelper
{

public static void CreateFolder(string path)
{
string dirPath = path.Substring(0, path.LastIndexOf("\\"));
if (!Directory.Exists(dirPath))
{
Directory.CreateDirectory(dirPath);
}

}

}

public class FileConnect : IDisposable
{

#region win32 API
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool LogonUser(string lpszUsername,string lpszDomain,string lpszPassword,int dwLogonType,int dwLogonProvider,ref IntPtr phToken);

[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool CloseHandle(IntPtr handle);

[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public extern static bool DuplicateToken(IntPtr existingTokenHandle,int SECURITY_IMPERSONATION_LEVEL,ref IntPtr duplicateTokenHandle);

// logon types
const int LOGON32_LOGON_INTERACTIVE = 2;
const int LOGON32_LOGON_NETWORK = 3;
const int LOGON32_LOGON_NEW_CREDENTIALS = 9;

// logon providers
const int LOGON32_PROVIDER_DEFAULT = 0;
const int LOGON32_PROVIDER_WINNT50 = 3;
const int LOGON32_PROVIDER_WINNT40 = 2;
const int LOGON32_PROVIDER_WINNT35 = 1;

WindowsIdentity newIdentity;
WindowsImpersonationContext impersonatedUser;
bool isSuccess = false;
IntPtr token = IntPtr.Zero;

public bool IsConnectted
{
get { return isSuccess; }
}

public FileConnect()
{
string fileServer = ConfigurationManager.AppSettings["FileServer"];  //远程服务器地址

if (!string.IsNullOrEmpty(fileServer))
{
isSuccess = Connect(fileServer, ConfigurationManager.AppSettings["FileServerUserName"], ConfigurationManager.AppSettings["FileServerPassword"]); //登录名 密码
}
else
{
isSuccess = true;
}
}

public bool Connect(string remoteAddr, string userName, string password)
{
bool isSuc = false;
try
{
isSuc = LogonUser(userName,remoteAddr, password, LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_DEFAULT, ref token);

newIdentity = new WindowsIdentity(token);
impersonatedUser = newIdentity.Impersonate();
}
catch (Exception )
{
return false;
}

return isSuc;
}

public void DisConnect()
{
if (isSuccess)
{
if (impersonatedUser != null)
impersonatedUser.Undo();
if (token != IntPtr.Zero)
CloseHandle(token);
}
}

public void Dispose()
{
DisConnect();
}

#endregion

}

}

---------------------------------------------

2.上传

public string uploadFileAndThumb(HttpContext context, string paramData, params object[] param)
{

using (FileConnect connect = new FileConnect())
{
string str_Result = "";
if (!connect.IsConnectted)
{
// throw new UException("");
str_Result = "{status:'fail',info:'文件服务器配置错误!'}";
return str_Result;
}

HttpPostedFile file = context.Request.Files["FileData"]; 
string extensionName = string.Empty;
string fileName = string.Empty;
if (file.FileName.LastIndexOf(".") > 0)
{
int len = file.FileName.LastIndexOf(".");
extensionName = file.FileName.Substring(len);

int lastIndex = file.FileName.LastIndexOf("\\");

if (lastIndex>0)
{
int subLength = len - 1 - lastIndex;
fileName = file.FileName.Substring(lastIndex+1, subLength);
}
else
{
//chorme
fileName = file.FileName.Substring(0, file.FileName.LastIndexOf("."));
}

}

string date = DateTime.Now.ToString("yyyyMMdd");

string pID="";
string relativePath = string.Format(@"\Project\{0}\{1}\", pID, date);
string FileFolder = System.Configuration.ConfigurationManager.AppSettings["FilePath"]; // 类似 \\10.2.183.21
string absoluteName = FileFolder + relativePath+ fileName+extensionName;
FileHelper.CreateFolder(absoluteName);

//判断文件大小
long length = file.ContentLength;
if (length > Convert.ToInt32(param[5]))
{
return "{ status:'100100',info:'' }";
}
else
{
file.SaveAs(absoluteName);
}

}

}

-------------------------------------------

3. 在需要下载附件 的页面 引用以下代码,登录远程服务器

//登录共享文件夹
using (FileConnect coneect = new FileConnect())
{
if (!coneect.IsConnectted)
{
// throw new UException("文件服务器配置错误");
}

}

--------------------------------------------

上一篇:shell 学习笔记9-while/until循环语句


下一篇:java的InputStream和OutputStream的理解【转】