공문서

28692 단어 C#ASP.NET
 #region            
        /// 
        ///            
        /// 
        ///         
        ///         
        /// 
        public static string DateDiff(DateTime DateTime1, DateTime DateTime2)
        {
            string dateDiff = null;

            TimeSpan ts1 = new TimeSpan(DateTime1.Ticks);
            TimeSpan ts2 = new TimeSpan(DateTime2.Ticks);
            TimeSpan ts = ts1.Subtract(ts2).Duration();
            dateDiff = ts.Days.ToString() + " "
                + ts.Hours.ToString() + "  "
                + ts.Minutes.ToString() + "  "
                + ts.Seconds.ToString() + " "
                + ts.TotalMilliseconds.ToString() + "  "
                ;

            return dateDiff;

            //  :
            //    1.DateTime           0001 1 1 0 0 0    9999 12 31 23 59 59          。  ,    DateTime                  。  DateTime           
            //    2.TimeSpan           ,         TimeSpan 
            //                  :
            //    Add:    TimeSpan   。 
            //    Days:        TimeSpan 。 
            //    Duration:  TimeSpan    。 
            //    Hours:        TimeSpan  
            //    Milliseconds:        TimeSpan 。 
            //    Minutes:        TimeSpan 。 
            //    Negate:          。 
            //    Seconds:       TimeSpan 。 
            //    Subtract:       TimeSpan 。 
            //    Ticks:  TimeSpan  tick 。 
            //    TotalDays:  TimeSpan      。 
            //    TotalHours:  TimeSpan       。 
            //    TotalMilliseconds:  TimeSpan       。 
            //    TotalMinutes:  TimeSpan       。 
            //    TotalSeconds:  TimeSpan      。 

        }

        #endregion

        #region       ,    HTML    

        /// 
        ///                    ,         TYPE_ERR            SIZE_ERR       FILE_ERR       /r/n
        ///string[] strfiletype = new string[] { "jpg" };/r/n
        ///string strResult = string.Empty;/r/n
        ///strResult = Public.Upload.UploadFile(Server.MapPath("/updatepath"), 999999, strfiletype, PhotoFile);/r/n
        ///if (strResult == "TYPE_ERR")/r/n
        ///{/r/n
        ///    alert.show(this.Page, "       ,        !");/r/n
        ///    return;/r/n
        /// }/r/n
        /// 
        ///     
        ///       
        ///     
        ///    
        ///               
        /// 
        public static string UploadFile(string filePath, int maxSize, string[] fileType, System.Web.UI.HtmlControls.HtmlInputFile TargetFile, string GetImgFileName)
        {
            string Result = "UnDefine";
            bool typeFlag = false;
            string FilePath = filePath;
            int MaxSize = maxSize;
            string strFileName, strNewName, strFilePath;
            if (TargetFile.PostedFile.FileName == "")
            {
                return "FILE_ERR";
            }
            strFileName = TargetFile.PostedFile.FileName;
            TargetFile.Accept = "*/*";
            strFilePath = FilePath;
            if (Directory.Exists(strFilePath) == false)
            {
                Directory.CreateDirectory(strFilePath);
            }
            FileInfo myInfo = new FileInfo(strFileName);
            string strOldName = myInfo.Name;
            strNewName = strOldName.Substring(strOldName.LastIndexOf('.') + 1, strOldName.Length - strOldName.LastIndexOf('.') - 1);
            strNewName = strNewName.ToLower();
            //            
            if (!GetMIMEByFileType(TargetFile.PostedFile.ContentType))
            {
                typeFlag = false;
                return "TYPE_ERR";
            }
            else
            {
                //if (TargetFile.PostedFile.ContentLength <= MaxSize)
                //{
                    for (int i = 0; i <= fileType.GetUpperBound(0); i++)
                    {
                        if (strNewName.ToLower() == fileType[i].ToString()) { typeFlag = true; break; }
                    }
                    if (typeFlag)
                    {
                        string strFileNameTemp = GetImgFileName;
                        string strFilePathTemp = strFilePath;
                        strOldName = strFileNameTemp + "." + strNewName;
                        strFilePath = strFilePath + strOldName;
                        TargetFile.PostedFile.SaveAs(strFilePath);

                        Result = strOldName;
                        TargetFile.Dispose();
                    }
                    else
                    {
                        return "TYPE_ERR";
                    }
                //}

                //else
                //{
                //    return "SIZE_ERR";
                //}
            }
            return (Result);
        }

        /// 
        ///             MIME  
        /// 
        ///      ,  .
        /// MIME  
        public static bool GetMIMEByFileType(string strfiletype)
        {
            switch (strfiletype.ToLower())
            {
                case "image/gif": return true;
                case "image/jpeg": return true;
                case "image/pjpeg": return true;
                case "image/png": return true;
                case "application/x-MS-bmp": return true;
                default:
                    return false;
            }
        }



        #endregion

        #region          , 1      2
        /// 
        ///          , 1      2
        /// 
        /// 
        public static int GetStringLength(string str)
        {
            return Encoding.Default.GetBytes(str).Length;
        }

        #endregion

        #region        2006-10-25 m
        /// 
        ///        ,       、      、   、       
        ///                、     、         
        /// 
        ///          
        /// 
        ///           (0    ,1              ,2              ,3                 
        /// 4      ,5      ,6            )
        /// 
        ///         


        public static string GetRandNumber(int len, int mod)
        {

            #region         
            int isnu = 0;
            int ulword = 0;
            switch (mod)
            {
                case 0:
                    isnu = 0;
                    break;
                case 1:
                    isnu = 1;
                    ulword = 0;
                    break;
                case 2:
                    isnu = 1;
                    ulword = 1;
                    break;
                case 3:
                    isnu = 1;
                    ulword = 2;
                    break;
                case 4:
                    isnu = 2;
                    ulword = 0;
                    break;
                case 5:
                    isnu = 2;
                    ulword = 1;
                    break;
                case 6:
                    isnu = 2;
                    ulword = 2;
                    break;
            }
            #endregion
            RNGCryptoServiceProvider rcsp = new RNGCryptoServiceProvider();
            string getcrypt = "";
            if (isnu == 0)
            {
                #region           
                byte[] Tarray = new byte[len];
                rcsp.GetNonZeroBytes(Tarray);
                string tstring = "";
                for (int i = 0; i < Tarray.Length; i++)
                {
                    tstring += Tarray[i].ToString();
                }
                Random rd = new Random();
                for (int cnt = 0; cnt < len; cnt++)
                {
                    getcrypt += tstring.Substring(rd.Next(0, tstring.Length), 1);
                }
                #endregion
            }
            else if (isnu == 1)
            {
                #region            
                byte[] Tarray = new byte[1];
                int tcon = 0;
                while (tcon < len)
                {
                    rcsp.GetNonZeroBytes(Tarray);
                    if (((char)Tarray[0] < 91 && (char)Tarray[0] > 64) || ((char)Tarray[0] < 123 && (char)Tarray[0] > 96))
                    {
                        getcrypt += ((char)Tarray[0]).ToString();
                        tcon++;
                    }
                    else if (((char)Tarray[0] < 58 && (char)Tarray[0] > 47))
                    {
                        getcrypt += Tarray[0].ToString();
                        tcon++;
                    }
                }
                if (ulword == 0)
                {
                    getcrypt = getcrypt.ToLower();
                    getcrypt = getcrypt.Substring(0, len);
                }
                else if (ulword == 1)
                {
                    getcrypt = getcrypt.ToUpper();
                    getcrypt = getcrypt.Substring(0, len);
                }
                #endregion
            }
            else if (isnu == 2)
            {
                #region         
                byte[] Tarray = new byte[1];
                int tcon = 0;
                while (tcon < len)
                {
                    rcsp.GetNonZeroBytes(Tarray);
                    if (((char)Tarray[0] < 91 && (char)Tarray[0] > 64) || ((char)Tarray[0] < 123 && (char)Tarray[0] > 96))
                    {
                        getcrypt += ((char)Tarray[0]).ToString();
                        tcon++;
                    }
                }
                if (ulword == 0)
                {
                    getcrypt = getcrypt.ToLower();
                }
                else if (ulword == 1)
                {
                    getcrypt = getcrypt.ToUpper();
                }
                #endregion
            }
            return getcrypt;
        }

        #endregion

        #region             [      /  /  ,          ] 2007-02-26 m

        public static string returnstring(string rcstring, int sublen)
        {
            //rcstring = rcstring.Trim().Replace(" ","").Replace(" ","");
            if (rcstring.Length < 1)
            {
                return "";
            }
            else
            {
                string rcstr = ToBj(rcstring);
                int intsob = 0;
                if (sublen >= rcstr.Length)
                {
                    return rcstr;
                }
                else
                {
                    //string strnew = string.Empty;
                    //string strnew = rcstr.Substring(0,sublen);
                    StringBuilder strnew = new StringBuilder(rcstr.Substring(0, sublen));
                    int strnewlength = strnew.Length;
                    for (int i = 0; i < strnewlength; i++)
                    {
                        if (IsBjChar(strnew[i]))
                        {
                            intsob++;
                        }
                    }
                    if (intsob != 0 && intsob > 1)
                    {
                        int inti = 0;
                        int struns = intsob / 2;
                        int strunsis = intsob % 2;
                        string tempstri = rcstr.Substring(sublen, rcstr.Length - sublen);
                        int cnt = 0;
                        int intbom = 0;
                        while (inti < struns)
                        {
                            if (cnt == tempstri.Length)
                            {
                                break;
                            }
                            if (IsBjChar(tempstri[cnt]))
                            {
                                intbom++;
                                if (strunsis == 1 && intbom == 1)
                                {
                                    inti++;
                                    strunsis = 0;
                                    intbom = 0;
                                }
                                else if (intbom == 2)
                                {
                                    inti++;
                                    intbom = 0;
                                }
                            }
                            else
                            {
                                inti++;
                            }
                            strnew.Append(tempstri[cnt].ToString());
                            cnt++;
                        }

                    }
                    if (sublen > 17)
                        return strnew.ToString() + "...";
                    else
                        return strnew.ToString();
                }
            }

            ///       10   
            ///        ,                       
        }
        /// 
        ///                
        /// 
        /// 
        /// 32         
        /// 33-47      
        /// 48-57    0~9
        /// 58-64      
        /// 65-90    A~Z
        /// 91-96      
        /// 97-122    a~z
        /// 123-126    
        /// 
        public static bool IsBjChar(char c)
        {
            int i = (int)c;
            return i >= 32 && i <= 126;
        }

        /**/
        /// 
        ///              
        /// 
        /// 
        ///      - 65248 =     
        ///       
        /// 
        public static bool IsQjChar(char c)
        {
            if (c == '\u3000') return true;

            int i = (int)c - 65248;
            if (i < 32) return false;
            return IsBjChar((char)i);
        }

        /**/
        /// 
        ///                
        /// 
        public static string ToBj(string s)
        {
            if (s == null || s.Trim() == string.Empty) return s;

            StringBuilder sb = new StringBuilder(s.Length);
            for (int i = 0; i < s.Length; i++)
            {
                if (s[i] == '\u3000')
                    sb.Append('\u0020');
                else if (IsQjChar(s[i]))
                    sb.Append((char)((int)s[i] - 65248));
                else
                    sb.Append(s[i]);
            }

            return sb.ToString();
        }
        #endregion

        #region                     

        /// 
        ///                     
        /// 
        ///     
        ///          
        ///        
        ///     
        public static string CutString(string str, int startIndex, int length)
        {
            if (startIndex >= 0)
            {
                if (length < 0)
                {
                    length = length * -1;
                    if (startIndex - length < 0)
                    {
                        length = startIndex;
                        startIndex = 0;
                    }
                    else
                    {
                        startIndex = startIndex - length;
                    }
                }


                if (startIndex > str.Length)
                {
                    return "";
                }


            }
            else
            {
                if (length < 0)
                {
                    return "";
                }
                else
                {
                    if (length + startIndex > 0)
                    {
                        length = length + startIndex;
                        startIndex = 0;
                    }
                    else
                    {
                        return "";
                    }
                }
            }

            if (str.Length - startIndex < length)
            {
                length = str.Length - startIndex;
            }

            return str.Substring(startIndex, length);
        }
        #endregion

        #region                        
        /// 
        ///                        
        /// 
        ///     
        ///          
        ///     
        public static string CutString(string str, int startIndex)
        {
            return CutString(str, startIndex, str.Length);
        }

        #endregion

        #region   JS  

        /// 
        ///           
        /// 
        //public class Alart
        //{
        /// 
        ///       
        /// 
        public enum AlartState
        {
            /// 
            ///           
            /// 
            OpenInParentWindow,
            /// 
            ///            
            /// 
            OpenInThisWindow,
            /// 
            ///         
            /// 
            Back,
            /// 
            ///     
            /// 
            CloseWindow,
            /// 
            ///       
            /// 
            Nothing
        }

        /// 
        ///   JS        WebSite.Components.Public.ShowAlart(Context, "      (  )    !", WebSite.Components.Public.AlartState.Nothing, Request.Url.ToString());
        /// 
        ///   Context
        ///     
        ///      *   
        ///        URL
        ///
        public static void ShowAlart(HttpContext context, string Msg, AlartState Astate, string ToUrl)
        {
            System.Text.StringBuilder mySB = new System.Text.StringBuilder();

            mySB.AppendFormat("alert('{0}');", Msg);

            switch (Astate)
            {
                case AlartState.Back:
                    mySB.Append("history.go(-1);");
                    break;

                case AlartState.CloseWindow:
                    mySB.Append("top.window.close();");
                    break;

                case AlartState.OpenInParentWindow:
                    mySB.AppendFormat("top.location = '{0}';", ToUrl);
                    break;

                case AlartState.OpenInThisWindow:
                    mySB.AppendFormat("window.location = '{0}';", ToUrl);
                    break;
                case AlartState.Nothing:
                    break;
            }

            mySB.Append("");

            context.Response.Write(mySB.ToString());

        }


        //}
        #endregion


        #region         

        #region   CONFIG  appSettings        

        /// 
        ///   CONFIG  appSettings        
        /// 
        ///   
        ///       GET_ERR     
        public static string GetConfigPar(string configName)
        {
            try
            {
                return System.Configuration.ConfigurationManager.AppSettings[configName].ToString();
            }
            catch
            {
                return "GET_ERR";
            }
        }
        #endregion

        #region         
        /// 
        ///  Setting.config     
        /// 
        /// 
        /// 
        /// 
        /// 
        static internal string GetConfigValue(string Target, string XmlPath)
        {
            System.Xml.XmlDocument xdoc = new XmlDocument();
            xdoc.Load(XmlPath);
            XmlElement root = xdoc.DocumentElement;
            XmlNodeList elemList = root.GetElementsByTagName(Target);
            return elemList[0].InnerXml;
        }
        #endregion

        #region   Setting.config     

        /// 
        ///  Setting.config     
        /// 
        /// 
        /// 
      public  static  string GetConfigValue(string Target)
        {
            string path = HttpContext.Current.Server.MapPath(@"~/Setting.config");
            return GetConfigValue(Target, path);
        }

        #endregion

        #region   CONFIG  appSettings      
        /// 
        ///   CONFIG  appSettings      
        /// 
        ///   
        ///   
        ///        SET_ERR       SET_SUC     
        public static string SetConfiParEng(string configName, string configValue)
        {
            try
            {//this.Request.ApplicationPath + 
                string file = HttpContext.Current.Server.MapPath(@"~\Web.config");
                XmlDocument document = new XmlDocument();
                document.Load(file);
                XmlNode node = document.SelectSingleNode("//add[@key = '" + configName + "']");
                node.Attributes[configName].Value = configValue;
                document.Save(file);

                return "SET_SUC";
            }
            catch
            {
                return "SET_ERR";
            }
        }

        #endregion

        #region          

        public static void SetConfiPar_E(string appSettingsName, string newValue)
        {
            string fileName = HttpContext.Current.Server.MapPath(@"~\Web.config");
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(fileName);
            XmlNodeList topM = xmlDoc.DocumentElement.ChildNodes;
            foreach (XmlElement element in topM)
            {
                #region       ,    

                if (element.Name == "appSettings")
                {
                    XmlNodeList node = element.ChildNodes;
                    if (node.Count > 0)
                    {
                        foreach (XmlElement el in node)
                        {
                            if (el.Attributes["key"].Value == appSettingsName)
                            {
                                el.Attributes["value"].Value = newValue;
                                xmlDoc.Save(fileName);
                                return;
                            }
                        }
                    }
                }

                #endregion
            }
        }

        #endregion

        #region          

        public static void SetConfiPar_3(string appSettingsName, string newValue)
        {
            string filename = HttpContext.Current.Server.MapPath(@"~\Web.config");
            XmlDocument xmldoc = new XmlDocument();
            xmldoc.Load(filename);

            XmlNodeList topM = xmldoc.DocumentElement.ChildNodes;
            foreach (XmlElement element in topM)
            {
                if (element.Name.ToLower() == "appsettings")
                {
                    XmlNodeList _node = element.ChildNodes;
                    if (_node.Count > 0)
                    {
                        foreach (XmlElement el in _node)
                        {
                            if (el.Attributes["key"].InnerXml.ToLower() == appSettingsName.ToLower())
                            {
                                el.Attributes["value"].Value = newValue;
                            }
                        }
                    }
                }

            }
            xmldoc.Save(filename);
        }

        #endregion

        #region       
        public static XmlDocument GetWebConfig()
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(GetXmlFileName());
            return xmlDoc;
        }
        #endregion

        #region   WEBCONFIG    
        public static string GetXmlFileName()
        {
            //  return HttpContext.Current.Server.MapPath(@"~\Web.config");
            return HttpContext.Current.Server.MapPath(@"~\Web.config");
        }
        #endregion

        #region          
        /// 
        ///          
        /// 
        /// 
        /// 
        public bool IsExistNode(string strNode)
        {
            XmlDocument xmlDoc = GetWebConfig();
            XmlNode xmlNode = xmlDoc.SelectSingleNode(@"/" + strNode);
            // retrieve the appSettings xmlNode   
            xmlNode = xmlDoc.SelectSingleNode("//" + strNode);
            return (xmlNode != null);
        }
        #endregion

        #region           
        /// 
        ///           
        /// 
        /// 
        /// 
        /// 
        public bool IsExistKey(string strNodeName, string strKey)
        {
            XmlDocument xmlDoc = GetWebConfig();
            bool IsExist = false;
            //            
            XmlNodeList topM = xmlDoc.DocumentElement.ChildNodes;
            foreach (XmlElement element in topM)
            {
                //        
                if (element.Name == strNodeName)
                {
                    XmlNodeList node = element.ChildNodes;
                    //           
                    if (node.Count > 0)
                    {
                        //         
                        foreach (XmlElement el in node)
                        {
                            //  Key        Liumm
                            IsExist = (el.Attributes["key"].InnerXml == strKey);
                            if (IsExist) break;
                        }
                    }

                }
            }
            return IsExist;

        }
        #endregion

        #region         

        /// 
        ///         
        /// 
        /// 
        /// 
        public static void SetConfiPar(string key, string value)
        {
            XmlDocument xmlDoc = GetWebConfig();
            XmlNode xmlNode = xmlDoc.SelectSingleNode(@"/appSettings");
            // retrieve the appSettings xmlNode   
            xmlNode = xmlDoc.SelectSingleNode("//appSettings");
            if (xmlNode == null)
            {
                throw new InvalidOperationException("appSettings section not found");
            }
            try
            {
                // XPath select setting "add" element that contains this key       
                XmlElement addElem = (XmlElement)xmlNode.SelectSingleNode("//add[@key='" + key + "']");
                if (addElem != null)
                {
                    addElem.SetAttribute("value", value);
                }
                // not found, so we need to add the element, key and value   
                else
                {
                    XmlElement entry = xmlDoc.CreateElement("add");
                    entry.SetAttribute("key", key);
                    entry.SetAttribute("value", value);
                    xmlNode.AppendChild(entry);
                }
                //save it   
                try
                {
                    XmlTextWriter writer = new XmlTextWriter(GetXmlFileName(), null);
                    writer.Formatting = Formatting.Indented;
                    xmlDoc.WriteTo(writer);
                    writer.Flush();
                    writer.Close();
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException(ex.Message);
            }
        }
        #endregion

        #endregion

좋은 웹페이지 즐겨찾기