zoukankan      html  css  js  c++  java
  • c# .net 监听磁盘映射 变更,及文件夹权限1

    <script type="text/javascript"> 
    window.setInterval(showalert, 10000); 
    function showalert() 
    {
        $.get("/Home/testsystemWatcher/", function (data) {//HOME这个Controllers下的监听方法
            //每隔3秒自动同步数据库
        });
    </script>
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using TestMVC.Models;
    using System.Data.SqlClient;
    using System.Collections;
    using TestMVC.Class;
    using System.IO;
    using System.Diagnostics;
    using System.Text;
    using System.Security.AccessControl;
    using System.Runtime.InteropServices;
    using System.DirectoryServices;
    using System.Threading;
    using System.Net;
    using System.Reflection;


    namespace TestMVC.Controllers
    {
        public class HomeController : Controller
        {
            //
            // GET: /Home/
            IPHostEntry myHost = new IPHostEntry();
            string stra = "";
            public ActionResult Index()
            {
                //userBLL userbll = new userBLL();
                //SqlDataReader iresult2 = userbll.getUsernameByIP(Request.UserHostAddress.ToString());
                //if (iresult2.Read())
                //{
                //    //设置COOCKIE
                //    HttpCookie myCookie = new HttpCookie(iresult2["userName"].ToString(), iresult2["userName"].ToString());
                //    Response.Cookies.Add(myCookie);
                //}
                //iresult2.Close();
                //iresult2.Dispose();

                //Dictionary<string, string> stackholder = new Dictionary<string, string>();
                //stackholder.Add("name", "value");
                //stackholder.Add("name1", "value1");
                //stackholder.Add("name2", "value2");
                //stackholder.Add("name3", "value3");
                //ViewData["stackholder"] = stackholder;
                string strresult = "登录失败";
                string strusername = Request["userName"];
                string userpwd = Request["userPwd"];
                userModel loginmodel = new userModel();
                userBLL userbll = new userBLL();
                SqlDataReader iresult = userbll.islogin(strusername, userpwd);
                if (iresult.Read())
                {
                    strresult = "登录成功";
                    //设置COOCKIE
                    HttpCookie myCookie = new HttpCookie("username", iresult["userName"].ToString());
                    Response.Cookies.Add(myCookie);
                }
                iresult.Close();
                iresult.Dispose();
                ViewBag.result = strusername + strresult;
                //ViewBag.strip = IPHostEntry.AddressList

                myHost = Dns.GetHostEntry(Dns.GetHostName());
                for (int i = 0; i < myHost.AddressList.Length; i++)
                {
                    if (myHost.AddressList[i].ToString().IndexOf("192.168") >= 0)
                    {
                        //stra += "本地主机IP地址->" + myHost.AddressList[i].ToString() + "-" + Request.UserHostAddress;
                        stra += Request.UserHostAddress;
                    }


                }
                SqlDataReader iresult2 = userbll.getUsernameByIP(Request.UserHostAddress.ToString());
                if (iresult2.Read())
                {
                    strresult = "登录成功";
                    //设置COOCKIE
                    HttpCookie myCookie = new HttpCookie(iresult2["userName"].ToString(), iresult2["userName"].ToString());
                    Response.Cookies.Add(myCookie);
                }
                iresult2.Close();
                iresult2.Dispose();



                ViewBag.strip = stra;

                return View();


            }

            #region 用户登录
            public string login()
            {
                string strresult = "登录失败";
                string strusername = Request["userName"];
                string userpwd = Request["userPwd"];
                userModel loginmodel = new userModel();
                userBLL userbll = new userBLL();
                SqlDataReader iresult = userbll.islogin(strusername, userpwd);
                if (iresult.Read())
                {
                    strresult = "登录成功";
                    //设置COOCKIE
                    HttpCookie myCookie = new HttpCookie("username", iresult["uid"].ToString());
                    Response.Cookies.Add(myCookie);
                }
                return strresult;
            }
            #endregion

            public ActionResult userList()
            {

                if (Request.Cookies["username"] != null)
                {
                    HttpCookie getusercookie = Request.Cookies["username"];//获取COOKIE中的值
                    if (!string.IsNullOrEmpty(getusercookie.Value))
                    {
                        string strusername = getusercookie.Value;
                    }
                }

                userBLL userbll = new userBLL();
                IList<userModel> luser = userbll.getlist();
                ViewData["luser"] = luser;
                return View();
            }

            #region 删除用户
            public string deluser()
            {
                string strresult = "删除失败";
                int uid = Request["uid"] != null ? Convert.ToInt32(Request["uid"]) : 0;
                userBLL userbll = new userBLL();
                int iresult = userbll.deluser(uid);
                if (iresult > 0)
                {
                    strresult = "删除成功";
                }
                return strresult.ToString();
            }
            #endregion

            #region 修改个人资料
            public string updateuser()
            {
                string strresult = "修改失败";
                int uid = Request["uid"] != null ? Convert.ToInt32(Request["uid"]) : 0;
                //string userpwd = Request["userPwd"];
                //userModel loginmodel = new userModel();
                userBLL userbll = new userBLL();
                //int iresult = userbll.deluser(uid);
                //if (iresult > 0)
                //{
                //    strresult = "修改成功";
                //}
                return strresult.ToString();
            }
            #endregion

            public string CreateDirectory()
            {



                //string path = "G:\";
                string path = "D:\iis2";
                uint state = 0;

                if (!Directory.Exists("Z:"))
                {

                    state = WNetHelper.WNetAddConnection(@"administrator", "654321", @"\192.168.1.225E: estweb1", "Z:");

                }

                if (state.Equals(0))
                {

                    Directory.CreateDirectory(path);//创建本地一个路径

                    Process process = new Process();
                    ProcessStartInfo startInfo = new ProcessStartInfo();
                    startInfo.FileName = " cmd.exe ";
                    startInfo.Arguments = @" /c E:o.bat";
                    startInfo.UseShellExecute = false;
                    startInfo.RedirectStandardInput = false;
                    startInfo.RedirectStandardOutput = false;
                    startInfo.CreateNoWindow = true;
                    process.StartInfo = startInfo;

                    process.Start();
                    //process.WaitForExit();
                    process.Dispose();
                    return "";

                }

                else
                {

                    throw new Exception("添加驱动器错误" + state.ToString());

                }

            }

            #region 映射服务器目录到本地磁盘
            public string WriteToFile()
            {
                string strresult = "";
                HttpCookie getusercookie = Request.Cookies["username"];//获取COOKIE中的值
                if (getusercookie == null)
                {
                    strresult = "请先登录";
                }
                else
                {
                    string username = getusercookie.Value;// "wyb";//当前登录用户名
                    string userpwd = "123456";//密码
                    //创建文件(user:用户名提取当前登录用户的ID做为远程登录的用户名。区别大小写)
                    System.IO.StreamWriter sw = new System.IO.StreamWriter(@"E:fabu1.bat");
                    sw.WriteLine("net use x: \\192.168.1.225\web2 "" + userpwd + "" /user:"" + username + """);
    // net use x: \192.168.1.225files "123456" /user:"intop_225user1" /persistent:yes //记住连接,开机自动连接
    //pause
                    sw.WriteLine("pause");
                    sw.Flush();
                    sw.Close();

                    string filePath = Server.MapPath("~/1.bat");//路径+文件名。这个路径要和上面的统一

                    FileStream fs = new FileStream(filePath, FileMode.Open);
                    byte[] bytes = new byte[(int)fs.Length];
                    fs.Read(bytes, 0, bytes.Length);
                    fs.Close();
                    Response.ContentType = "application/octet-stream";
                    Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode("1.bat", System.Text.Encoding.UTF8));
                    Response.BinaryWrite(bytes);
                    Response.Flush();
                    Response.End();

                    //首先清除其他连接会话
                    Process processClear = new Process();
                    ProcessStartInfo startInfoClear = new ProcessStartInfo();
                    startInfoClear.FileName = " cmd.exe ";
                    startInfoClear.Arguments = @" /c E:fabuclear.bat";
                    startInfoClear.UseShellExecute = false;
                    startInfoClear.RedirectStandardInput = false;
                    startInfoClear.RedirectStandardOutput = false;
                    startInfoClear.CreateNoWindow = true;
                    processClear.StartInfo = startInfoClear;
                    processClear.Start();
                    //process.WaitForExit();无限期等待执行
                    processClear.Dispose();

                    执行文件
                    //Process process = new Process();
                    //ProcessStartInfo startInfo = new ProcessStartInfo();
                    //startInfo.FileName = " cmd.exe ";
                    //startInfo.Arguments = @" /c E:mingling1.bat";
                    //startInfo.UseShellExecute = false;
                    //startInfo.RedirectStandardInput = false;
                    //startInfo.RedirectStandardOutput = false;
                    //startInfo.CreateNoWindow = true;
                    //process.StartInfo = startInfo;
                    //process.Start();
                    process.WaitForExit();
                    //process.Dispose();
                }

                return strresult;
            }
            #endregion

            #region 移除磁盘映射
            public string DelWriteToFile()
            {
                System.IO.StreamWriter sw = new System.IO.StreamWriter(@"E:fabu-1.bat");
                sw.WriteLine("net use x: /delete");
                sw.WriteLine("pause");
                sw.Flush();
                sw.Close();

                string filePath = Server.MapPath("~/-1.bat");//路径+文件名

                FileStream fs = new FileStream(filePath, FileMode.Open);
                byte[] bytes = new byte[(int)fs.Length];
                fs.Read(bytes, 0, bytes.Length);
                fs.Close();
                Response.ContentType = "application/octet-stream";
                Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode("-1.bat", System.Text.Encoding.UTF8));
                Response.BinaryWrite(bytes);
                Response.Flush();
                Response.End();

                //Process process = new Process();
                //ProcessStartInfo startInfo = new ProcessStartInfo();
                //startInfo.FileName = " cmd.exe ";
                //startInfo.Arguments = @" /c E:mingling-1.bat";
                //startInfo.UseShellExecute = false;
                //startInfo.RedirectStandardInput = false;
                //startInfo.RedirectStandardOutput = false;
                //startInfo.CreateNoWindow = true;
                //process.StartInfo = startInfo;

                //process.Start();
                process.WaitForExit();
                //process.Dispose();
                return "";
            }
            #endregion

            #region 本地映射磁盘与服务器同步(同步增删改查)
            /// <summary>
            /// 本地映射磁盘与服务器同步(同步增删改查)
            /// </summary>
            /// <returns></returns>
            public string toCallServer()
            {
                //循环文件夹及文件,和SQL里条数对比
                FilesBLL filesbll = new FilesBLL();
                string str = "";
                string str1 = "";
                string str2 = "";
                string path = @"E:web2";
                HttpCookie getusercookie = Request.Cookies["ipadd"];//获取COOKIE中的值
                if (!string.IsNullOrEmpty(getusercookie.Value))
                {
                    stra = getusercookie.Value;
                }
                string loginname = stra;//当前系统登录者的名称(此外需要用Cookie里的IP转化成用户名)
                DirectoryInfo thisOne = new DirectoryInfo(path);
                str1 = GetFile1(thisOne, 0, str1);
                str2 = GetFile2(thisOne, 0, str2);
                str = str1 + str2;
                str = str.Substring(0, str.Length - 1);//去掉最后一个拼接符^
                string[] zustr = str.Split('^');//以拼接符^分隔出来文件名
                try
                {
                    foreach (string strone in zustr)
                    {
                        //此处,拿文件名去匹配数据库文件表,是否有同样名称及目录的文件
                        SqlDataReader iresult = filesbll.checkFile(strone.Split('&')[0], strone.Split('&')[1]);
                        if (iresult.Read())
                        {
                            //如果数据库里有文件名且路径与本地一致,再查检最后修改时间同否一致(以后再做此功能)
                        }
                        else
                        {
                            //如果文件名及文件完整路径,数据库里没有匹配项,则表示本地新增文件,则自动在数据库里增加一条记录
                            int isresult = filesbll.add(strone.Split('&')[0], loginname, strone.Split('&')[1]);
                            //数据库里同步成功新增isresult++条
                        }

                        string strname = strone;
                    }
                    //如果数据库里记录比本地条数多,则表示本地文件已删除,数据库也同步删除
                    string strToSQL = "";
                    IList<FilesModel> lfiles = filesbll.getlist();
                    foreach (FilesModel model in lfiles)
                    {
                        strToSQL = model.fiName + "&" + model.fiPath;//根本本地拼接方法一致(文件名&完整路径)
                        if (str.IndexOf(strToSQL) < 0)//如果本地文件列表中没有数据库中某一条,表示本地文件已删除,此时数据库也同步删除
                        {
                            int isresult = filesbll.delFile("and fiName='" + model.fiName + "' and fiPath='" + model.fiPath + "' ");
                            //数据库里同步删除成功isresult++条
                        }
                    }
                }
                catch (Exception ex)
                {

                    string filePath = @"D:/TempExceptions.txt";
                    StreamWriter sw = System.IO.File.AppendText(filePath);
                    sw.Write(" " + "错误信息:" + ex.ToString() + " 时间:" + System.DateTime.Now + " " + " ");
                    sw.Close();
                }
                return str;
            }
            #endregion

            #region 获取指定文件夹下所有子目录下的文件(不包括指定目录根目录下的文件)
            /// <summary>
            /// 获取指定文件夹下所有子目录下的文件(不包括指定目录根目录下的文件)
            /// </summary>
            /// <param name="theDir">指定目录</param>
            /// <param name="nLevel">默认起始值,调用时,一般为0</param>
            /// <param name="Rn">用于迭加的传入值,一般为空</param>
            /// <returns></returns>
            public static string GetFile1(DirectoryInfo theDir, int nLevel, string Rn)//递归目录 文件
            {
                DirectoryInfo[] subDirectories = theDir.GetDirectories();//获得目录
                foreach (DirectoryInfo dirinfo in subDirectories)
                {
                    FileInfo[] fileInfo = dirinfo.GetFiles();   //目录下的文件
                    foreach (FileInfo fInfo in fileInfo)
                    {
                        if (fInfo.Name.ToString().IndexOf("~$") < 0)//排除临时缓存文件
                        {
                            Rn += fInfo.Name.ToString() + "&" + fInfo.FullName.ToString() + "^";//以&作为文件和文件名的分隔符,以^号作为每个文件的分隔符
                        }
                    }
                    Rn = GetFile1(dirinfo, nLevel + 1, Rn);
                }
                return Rn;
            }
            #endregion

            #region 获取指定目录根目录下的文件
            /// <summary>
            /// 获取指定目录根目录下的文件
            /// </summary>
            /// <param name="theDir">指定目录</param>
            /// <param name="nLevel">默认起始值,调用时,一般为0</param>
            /// <param name="Rn">用于迭加的传入值,一般为空</param>
            /// <returns></returns>
            public static string GetFile2(DirectoryInfo theDir, int nLevel, string Rn)//递归目录 文件
            {
                FileInfo[] fileInfo2 = theDir.GetFiles();   //目录下的文件
                foreach (FileInfo fInfo in fileInfo2)
                {
                    if (fInfo.Name.ToString().IndexOf("~$") < 0)//排除临时缓存文件
                    {
                        Rn += fInfo.Name.ToString() + "&" + fInfo.FullName.ToString() + "^";以&作为文件和文件名的分隔符,以^号作为每个文件的分隔符
                    }
                }
                return Rn;
            }
            #endregion

            //用户标志 
            private enum UserFlags
            {
                UF_SCRIPT = 0x0001,
                UF_ACCOUNTDISABLE = 0x0002,
                UF_HOMEDIR_REQUIRED = 0x0008,
                UF_LOCKOUT = 0x0010,
                UF_PASSWD_NOTREQD = 0x0020,
                UF_PASSWD_CANT_CHANGE = 0x0040,
                UF_TEMP_DUPLICATE_ACCOUNT = 0x0100,
                UF_NORMAL_ACCOUNT = 0x0200,
                UF_DONT_EXPIRE_PASSWD = 0x10000,
                UF_PASSWORD_EXPIRED = 0x800000
            }

            #region 新建一个用户
            /// <summary>
            /// 新建一个用户
            /// </summary>
            /// <param name="userName">用户名</param>
            /// <param name="userPass">密码</param>
            /// <param name="userComment">用户说明</param>
            /// <param name="userGroup">用户组</param>
            /// <returns></returns>
            public bool UserAdd(string userName, string userPass, string userComment, string userGroup)
            {
                try
                {
                    userName = Request["userName"].ToString();//要创建的计算机用户名
                    userPass = Request["userPwd"].ToString();//用户密码
                    userComment = "shuoming";
                    userGroup = "Administrators";//先默认属于管理员组
                    DirectoryEntry AD = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer");
                    //create user 
                    DirectoryEntry NewUser = AD.Children.Add(userName, "user");
                    //set password 
                    NewUser.Invoke("SetPassword", new object[] { userPass });
                    //set comment 
                    NewUser.Invoke("Put", new object[] { "Description", userComment });
                    //save 
                    NewUser.CommitChanges();
                    //add user to group 
                    DirectoryEntry grp = AD.Children.Find(userGroup, "group");
                    if (grp != null)
                    {
                        grp.Invoke("Add", new object[] { NewUser.Path.ToString() });
                    }
                    return true;
                }
                catch (Exception ex) { return false; }
            }
            #endregion

            #region 新建一个组
            /// <summary>
            /// 新建一个组
            /// </summary>
            /// <param name="groupName">用户组名</param>
            /// <param name="groupComment">组说明</param>
            /// <returns></returns>
            public bool GroupAdd(string groupName, string groupComment)
            {
                try
                {
                    groupName = Request["groupName"].ToString();//要创建的计算机用户组名
                    groupComment = Request["groupComment"].ToString();//要创建的计算机用户组说明
                    DirectoryEntry AD = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer");
                    //create group 
                    DirectoryEntry NewGroup = AD.Children.Add(groupName, "group");
                    //set comment 
                    NewGroup.Invoke("Put", new object[] { "Description", groupComment });
                    //save 
                    NewGroup.CommitChanges(); return true;
                }
                catch (Exception ex) { return false; }
            }
            #endregion

            //将用户添加到组 
            public static bool UserAddToGroup(string userName, string groupName)
            {
                try
                {
                    DirectoryEntry AD = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer");
                    DirectoryEntry user = AD.Children.Find(userName, "user");
                    DirectoryEntry grp = AD.Children.Find(groupName, "group");
                    grp.Invoke("Add", new object[] { user.Path.ToString() }); return true;
                }
                catch (Exception ex) { return false; }
            }
            //修改用户密码 
            public static bool UserSetPassword(string userName, string userPass)
            {
                try
                {
                    DirectoryEntry AD = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer");
                    //create user 
                    DirectoryEntry user = AD.Children.Find(userName, "user");
                    //set  password 
                    user.Invoke("SetPassword", new object[] { userPass });
                    user.CommitChanges(); return true;
                }
                catch (Exception ex) { return false; }
            }
            //启用用户 
            public bool UserEnable(string userName)
            {
                try
                {
                    userName = Request["userName"].ToString();//要创建的计算机用户名
                    DirectoryEntry user = new DirectoryEntry("WinNT://" + Environment.MachineName + "/" + userName + ",user");
                    user.Properties["UserFlags"].Value = ((int)user.Properties["userFlags"].Value) ^ (int)UserFlags.UF_ACCOUNTDISABLE; user.CommitChanges(); user.Close(); return true;
                }
                catch (Exception ex) { return false; }
            }
            //禁用用户 
            public static bool UserDisable(string userName)
            {
                try
                {
                    DirectoryEntry user = new DirectoryEntry("WinNT://" + Environment.MachineName + "/" + userName + ",user");
                    user.Properties["UserFlags"].Value = ((int)user.Properties["userFlags"].Value) | (int)UserFlags.UF_ACCOUNTDISABLE; user.CommitChanges(); user.Close(); return true;
                }
                catch (Exception ex) { return false; }
            }
            //删除用户 
            public static bool UserDel(string userName)
            {
                try
                {
                    DirectoryEntry localDirectory = new DirectoryEntry("WinNT://" + Environment.MachineName.ToString());
                    DirectoryEntries users = localDirectory.Children; DirectoryEntry user = users.Find(userName, "user"); users.Remove(user); return true;
                }
                catch (Exception ex) { return false; }
            }
            //删除组 
            public static bool GroupDel(string groupName)
            {
                try
                {
                    DirectoryEntry localDirectory = new DirectoryEntry("WinNT://" + Environment.MachineName.ToString());
                    DirectoryEntries groups = localDirectory.Children; DirectoryEntry group = groups.Find(groupName, "group"); groups.Remove(group); return true;
                }
                catch (Exception ex) { return false; }
            }
            //在这里新增函数 


  • 相关阅读:
    url 编码与解码
    调硬件开门
    JsBridge 开灯关灯
    滚动条样式
    uni-app 组件传值及插槽
    Eapp 调接口及跳转
    uni-app 的基础格式
    Eapp 几个弹框
    flexible 移动端适配
    mongodb恢复备份
  • 原文地址:https://www.cnblogs.com/wybshyy/p/13783892.html
Copyright © 2011-2022 走看看