当前位置: 首页>>代码示例>>C#>>正文


C# String.IsNullOrEmpty方法代码示例

本文整理汇总了C#中System.String.IsNullOrEmpty方法的典型用法代码示例。如果您正苦于以下问题:C# String.IsNullOrEmpty方法的具体用法?C# String.IsNullOrEmpty怎么用?C# String.IsNullOrEmpty使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.String的用法示例。


在下文中一共展示了String.IsNullOrEmpty方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: ParamInfo

 // note. we need this constructor to provide information
 // about method's parameters without having to decompile it
 //
 // the point is that to get sig's symbols we've got to know their ids
 // but the ids need to be synchronized with Refs in decompiled body
 // that's why a simple call to Sig::Syms need to decompile the entire body
 public ParamInfo(Sig sig, int index, String name, Type type)
 {
     Sig = sig;
     Index = index;
     Name = name.IsNullOrEmpty() ? "$p" + index : name;
     Type = type;
 }
开发者ID:xeno-by,项目名称:truesight-lite,代码行数:13,代码来源:ParamInfo.cs

示例2: DecryptString

        public static String DecryptString(String Text, String Key)
        {
            if (Text.IsNullOrEmpty())
                throw new BPAExtensionException("DecryptString Text Not Found!");

            RijndaelManaged RijndaelCipher = new RijndaelManaged();

            byte[] EncryptedData = Convert.FromBase64String(Text.Replace("_", "/").Replace("-", "+"));
            byte[] Salt = new UTF8Encoding().GetBytes(Key.Length.ToString());

            PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(Key, Salt);
            ICryptoTransform Decryptor = RijndaelCipher.CreateDecryptor(SecretKey.GetBytes(16), SecretKey.GetBytes(16));
            MemoryStream memoryStream = new MemoryStream(EncryptedData);
            CryptoStream cryptoStream = new CryptoStream(memoryStream, Decryptor, CryptoStreamMode.Read);

            byte[] PlainText = new byte[EncryptedData.Length];
            int DecryptedCount = cryptoStream.Read(PlainText, 0, PlainText.Length);

            memoryStream.Close();
            cryptoStream.Close();

            String DecryptedData = new UTF8Encoding().GetString(PlainText, 0, DecryptedCount);

            if (HttpContext.Current != null)
                return HttpContext.Current.Server.HtmlDecode(DecryptedData);
            else
                return DecryptedData;
        }
开发者ID:rafaelberrocalj,项目名称:BPA,代码行数:28,代码来源:EncryptDecrypt.cs

示例3: HTTPBasicAuthentication

        /// <summary>
        /// Create the credentials based on a base64 encoded string which comes from a HTTP header Authentication:
        /// </summary>
        /// <param name="HTTPHeaderCredential"></param>
        public HTTPBasicAuthentication(String HTTPHeaderCredential)
        {
            #region Initial checks

            if (HTTPHeaderCredential.IsNullOrEmpty())
                throw new ArgumentNullException("HTTPHeaderCredential", "The given credential string must not be null or empty!");

            #endregion

            var splitted = HTTPHeaderCredential.Split(new[] { ' ' });

            if (splitted.IsNullOrEmpty())
                throw new ArgumentException("invalid credentials " + HTTPHeaderCredential);

            if (splitted[0].ToLower() == "basic")
            {

                HTTPCredentialType = HTTPAuthenticationTypes.Basic;
                var usernamePassword = splitted[1].FromBase64().Split(new[] { ':' });

                if (usernamePassword.IsNullOrEmpty())
                    throw new ArgumentException("invalid username/password " + splitted[1].FromBase64());

                Username = usernamePassword[0];
                Password = usernamePassword[1];

            }

            else
                throw new ArgumentException("invalid credentialType " + splitted[0]);
        }
开发者ID:subbuballa,项目名称:Hermod,代码行数:35,代码来源:HTTPBasicAuthentication.cs

示例4: PrettyPrintImpl

        private IEnumerable<String> PrettyPrintImpl(String js)
        {
            var newLineDelims = new []{".Select(", ".Where(", ".OrderBy(", ".GroupBy"};
            Func<int> delimPos = () => js.IsNullOrEmpty() ? -1 : newLineDelims
                .Select(delim => js.IndexOf(delim,1 ))
                .Aggregate(-1, (running, curr) => curr <= 0 ? 
                    running : (running == -1 ? curr : Math.Min(running, curr)));

            while(delimPos() != -1)
            {
                yield return js.Substring(0, delimPos()).ToVerbatimCSharpCopy();
                js = js.Substring(delimPos());
            }

            if (!js.IsNullOrEmpty()) 
                yield return js;
        }
开发者ID:xeno-by,项目名称:relinq,代码行数:17,代码来源:RelinqScriptBuilderTests.cs

示例5: Img

        /// <summary>
        /// Example: String.Format("/Utility/Img/{0}?width=300&height=100", Utility.ImageGetHash("img", "img_contenttye", "photo", "id_photo", "1"));
        /// "?width=300&height=100" is optional but when used need to send both
        /// </summary>
        /// <param name="id">"id" is the default MVC param</param>
        /// <returns>The Image to be Displed</returns>
        public ActionResult Img(String id)
        {
            if (id.IsNullOrEmpty())
                return View();

            System.Web.HttpContext hc = System.Web.HttpContext.Current;

            try
            {
                String[] spl = Security.DecryptString(id, Security.Key).Split('#');

                Hashtables lst = DBAction.Select(
                    String.Format("SELECT {0}, {1} FROM {2} WHERE {3} = #id ", spl[0], spl[1], spl[2], spl[3]),
                    new Parameters()
                    {
                        new Parameter("#id", spl[4], System.Data.DbType.Int32)
                    }
                );

                Stream s = new MemoryStream((byte[])lst[0][spl[0]]);

                byte[] b;

                if (hc.Request.QueryString.Count == 0)
                {
                    b = ((MemoryStream)s).ToArray();
                }
                else
                {
                    Image img = Image.FromStream(s);

                    img = ImageUtility.FixedSize(img, hc.Request.QueryString["width"].ToInt32(), hc.Request.QueryString["height"].ToInt32());

                    MemoryStream ms = new MemoryStream();

                    img.Save(ms, ImageFormat.Jpeg);

                    b = ms.ToArray();
                }

                hc.Response.Clear();

                hc.Response.ContentType = lst[0][spl[1]].ToString();
                hc.Response.BinaryWrite(b);
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                hc.Response.End();
            }

            return View();
        }
开发者ID:rafaelberrocalj,项目名称:BPA,代码行数:62,代码来源:UtilityController.cs

示例6: AddNode

        public static INode AddNode(this IGraph myIGraph, String myId)
        {
            if (myIGraph == null)
                throw new ArgumentNullException("myIGraph must not be null!");

            if (myId.IsNullOrEmpty())
                throw new ArgumentNullException("myId must not be null or empty!");

            return myIGraph.AddNode(new Node(myId));
        }
开发者ID:subbuballa,项目名称:Walkyr,代码行数:10,代码来源:IGraphExtensions.cs

示例7: NaturalLanguageProcessor

        public NaturalLanguageProcessor(String language = null)
        {
            if (language.IsNullOrEmpty())
            {
                language = CultureInfo.CurrentUICulture.TwoLetterISOLanguageName;
            }

            _positionOfSpeechTags = PositionOfSpeechTags.CreatePositionOfSpeechTags(language);

            _language = language;
        }
开发者ID:danielcamargo,项目名称:dotnet.showcase,代码行数:11,代码来源:NaturalLanguageProcessor.cs

示例8: CheckCNPJ

        private static Boolean CheckCNPJ(String CNPJ)
        {
            if (CNPJ.IsNullOrEmpty())
                return false;

            int[] multiplicador1 = new int[12] { 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2 };
            int[] multiplicador2 = new int[13] { 6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2 };

            int soma;
            int resto;

            string digito;
            string tempCnpj;

            CNPJ = CNPJ.Trim().Replace(".", "").Replace("-", "").Replace("/", "");

            if (CNPJ.Length != 14)
                return false;

            tempCnpj = CNPJ.Substring(0, 12);

            soma = 0;

            for (int i = 0; i < 12; i++)
                soma += int.Parse(tempCnpj[i].ToString()) * multiplicador1[i];

            resto = (soma % 11);

            if (resto < 2)
                resto = 0;
            else
                resto = 11 - resto;

            digito = resto.ToString();

            tempCnpj = tempCnpj + digito;

            soma = 0;

            for (int i = 0; i < 13; i++)
                soma += int.Parse(tempCnpj[i].ToString()) * multiplicador2[i];

            resto = (soma % 11);

            if (resto < 2)
                resto = 0;
            else
                resto = 11 - resto;

            digito = digito + resto.ToString();

            return CNPJ.EndsWith(digito);
        }
开发者ID:rafaelberrocalj,项目名称:BPA,代码行数:53,代码来源:ValidationMethods.cs

示例9: PaintImageCell

        /// <summary>
        /// Repaint an image cell with an image in an image
        /// list. Run this method in the CellPainting event
        /// of the DataGridView.
        /// 
        /// This method ignores invalid parameters. Provide
        /// it with empty or invalid indices to cause it to
        /// abort.
        /// </summary>
        public static void PaintImageCell(this DataGridView dataGridView, DataGridViewCellPaintingEventArgs e, ImageList imageList, String imageKey)
        {
            //Abort if any parameter is null or if the image does not exist
            if (e == null || imageList == null || imageKey.IsNullOrEmpty())
                return;
            if (!imageList.Images.ContainsKey(imageKey))
                return;

            //Paint the image
            e.PaintBackground(e.ClipBounds, false);
            var pt = e.CellBounds.Location;
            pt.X += (e.CellBounds.Width - imageList.ImageSize.Width) / 2;
            pt.Y += 4;
            imageList.Draw(e.Graphics, pt, imageList.Images.IndexOfKey(imageKey));
            e.Handled = true;
        }
开发者ID:xlongtang,项目名称:nextra,代码行数:25,代码来源:DataGridView_Extensions.cs

示例10: HTTPBasicAuthentication

        /// <summary>
        /// Create the credentials based on a base64 encoded string which comes from a HTTP header Authentication:
        /// </summary>
        /// <param name="Username">The username.</param>
        /// <param name="Password">The password.</param>
        public HTTPBasicAuthentication(String  Username,
                                       String  Password)
        {
            #region Initial checks

            if (Username.IsNullOrEmpty())
                throw new ArgumentNullException(nameof(Username), "The given username must not be null or empty!");

            if (Password.IsNullOrEmpty())
                throw new ArgumentNullException(nameof(Password), "The given password must not be null or empty!");

            #endregion

            this._HTTPCredentialType  = HTTPAuthenticationTypes.Basic;
            this._Username            = Username;
            this._Password            = Password;
        }
开发者ID:Vanaheimr,项目名称:Hermod,代码行数:22,代码来源:HTTPBasicAuthentication.cs

示例11: PrepareView

        public static string PrepareView(this ControllerBase controller, Object model, String viewName = null)
        {
            if (model == null) throw new ArgumentNullException("model");

            if (viewName == null) throw new ArgumentNullException("viewName");

            if (viewName.IsNullOrEmpty())
            {
                viewName = controller.ControllerContext.RouteData.GetRequiredString("action");
            }

            var viewPath = GetVirtualViewPath(controller, viewName);

            var result = RenderRazorViewToString(controller, viewPath, model);

            return result;
        }
开发者ID:GhostPubs,项目名称:GhostPubsMvc4,代码行数:17,代码来源:ControllerBaseExtensions.cs

示例12: DeleteStartAndEndTokens

        /// <summary>
        /// Удаляет из входной строки указанную начальную и конечную подстроки, если они есть. Если нет хотя бы одной из них, то возвращается исходная строка. 
        /// Если во входной строке содержится множество вложенных один в другой начальных и конечных токенов, метод удалит их все рекурсивно.
        /// </summary>
        /// <param name="Input">Входная строка, из которой необходимо удалить все указанные начальные и конечные токены.</param>
        /// <param name="StartToken">Начальный токен</param>
        /// <param name="EndToken">Конечный токен</param>
        /// <param name="CompOpt"></param>
        /// <returns>Новая строка, содержащая копию старой с удалёнными токенами</returns>
        public static String DeleteStartAndEndTokens(String Input, String StartToken, String EndToken, StringComparison CompOpt)
        {
            if (StartToken.IsNullOrEmpty() == true) { throw new ArgumentException("Начальный токен не может быть NULL или пустой строкой", "Input"); }
            if (EndToken == null) { throw new ArgumentException("Конечный токен не может быть NULL или пустой строкой", "EndToken"); }

            if (Input.IsStringNullEmptyWhiteSpace() == true) { return Input; }

            if (Input.StartsWith(StartToken, CompOpt) == true && Input.EndsWith(EndToken, CompOpt) == true)
            {
                Input = Input.Remove(0, StartToken.Length);
                Input = Input.Remove(Input.Length - EndToken.Length, EndToken.Length);
                return DeleteStartAndEndTokens(Input, StartToken, EndToken, CompOpt);
            }
            else
            {
                return Input;
            }
        }
开发者ID:Klotos,项目名称:KlotosLib,代码行数:27,代码来源:SubstringHelpers.cs

示例13: Save

        /// <summary>
        /// Stores the given IGEXF graph on disk
        /// </summary>
        /// <param name="myFileName">The filename for storing the graph</param>
        public static IGEXF Save(this IGEXF myIGEXF, String myFileName)
        {
            #region Initial checks

            if (myIGEXF == null)
                throw new ArgumentNullException("myIGEXF must not be null!");

            if (myFileName.IsNullOrEmpty())
                throw new ArgumentNullException("myFileName must not be null!");

            #endregion

            if (!myFileName.Contains("."))
                myFileName += ".gexf";

            myIGEXF.ToXML().Save(myFileName);

            return myIGEXF;
        }
开发者ID:subbuballa,项目名称:Walkyr,代码行数:23,代码来源:IGEXFExtensions.cs

示例14: Download

        /// <summary>
        /// Example: String.Format("/Utility/Download/{0}", Utility.DownloadGetHash("img", "img_contenttype", "img_name", "photos", "id_photo", "1"));
        /// </summary>
        /// <param name="id">"id" is the default MVC param</param>
        /// <returns>The File to be Downloaded</returns>
        public ActionResult Download(String id)
        {
            if (id.IsNullOrEmpty())
                return View();

            System.Web.HttpContext hc = System.Web.HttpContext.Current;

            try
            {
                String[] spl = Security.DecryptString(id, Security.Key).Split('#');

                Hashtables lst = DBAction.Select(
                    String.Format("SELECT {0}, {1}, {2} FROM {3} WHERE {4} = #id ", spl[0], spl[1], spl[2], spl[3], spl[4]),
                    new Parameters()
                    {
                        new Parameter("#id", spl[5], System.Data.DbType.Int32)
                    }
                );

                Stream s = new MemoryStream((byte[])lst[0][spl[0]]);

                hc.Response.Clear();

                hc.Response.AddHeader("Content-Disposition", "attachment; filename=" + lst[0][spl[2]].ToString().Replace(" ", "_"));
                hc.Response.AddHeader("Content-Length", s.Length.ToString());
                hc.Response.ContentType = lst[0][spl[2]].ToString();
                hc.Response.BinaryWrite(((MemoryStream)s).ToArray());
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                hc.Response.End();
            }

            return View();
        }
开发者ID:rafaelberrocalj,项目名称:BPA,代码行数:44,代码来源:UtilityController.cs

示例15: LoadPlugin

        /// <summary>加载插件</summary>
        /// <param name="typeName"></param>
        /// <param name="disname"></param>
        /// <param name="dll"></param>
        /// <param name="linkName"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        public static Type LoadPlugin(String typeName, String disname, String dll, String linkName, String url)
        {
            var type = typeName.GetTypeEx(true);
            if (type != null) return type;

            if (dll.IsNullOrEmpty()) return null;

            // 先检查当前目录,再检查插件目录
            var file = dll.GetFullPath();
            if (!File.Exists(file) && Runtime.IsWeb) file = "Bin".GetFullPath().CombinePath(dll);
            if (!File.Exists(file)) file = Setting.Current.GetPluginPath().CombinePath(dll);

            // 如果本地没有数据库,则从网络下载
            if (!File.Exists(file))
            {
                XTrace.WriteLine("{0}不存在或平台版本不正确,准备联网获取 {1}", disname ?? dll, url);

                var client = new WebClientX(true, true);
                client.Log = XTrace.Log;
                var dir = Path.GetDirectoryName(file);
                var file2 = client.DownloadLinkAndExtract(url, linkName, dir);
            }
            if (!File.Exists(file))
            {
                XTrace.WriteLine("未找到 {0} {1}", disname, dll);
                return null;
            }

            type = typeName.GetTypeEx(true);
            if (type != null) return type;

            //var assembly = Assembly.LoadFrom(file);
            //if (assembly == null) return null;

            //type = assembly.GetType(typeName);
            //if (type == null) type = AssemblyX.Create(assembly).GetType(typeName);
            return type;
        }
开发者ID:tommybiteme,项目名称:X,代码行数:45,代码来源:PluginHelper.cs


注:本文中的System.String.IsNullOrEmpty方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。