C# 如何将字符串的内容限制在4MB以下,并使用C将该字符串保存在DB中

C# 如何将字符串的内容限制在4MB以下,并使用C将该字符串保存在DB中,c#,string,pdf,itextsharp,C#,String,Pdf,Itextsharp,我正在做一个项目,我需要从pdf文件中获取文本数据,并将整个文本转储到DB列中。在iTextsharp的帮助下,我得到了数据并将其引用到字符串中 但是现在我需要检查字符串是否超过4MB限制,如果超过了,那么接受小于4MB的字符串数据 这是我的代码: internal string ReadPdfFiles() { // variable to store file path string filePath = null; // open dial

我正在做一个项目,我需要从pdf文件中获取文本数据,并将整个文本转储到DB列中。在iTextsharp的帮助下,我得到了数据并将其引用到字符串中

但是现在我需要检查字符串是否超过4MB限制,如果超过了,那么接受小于4MB的字符串数据

这是我的代码:

internal string ReadPdfFiles()
{
        // variable to store file path
        string filePath = null;

        // open dialog box to select file
        OpenFileDialog file = new OpenFileDialog();

        // dilog box title name
        file.Title = "Select Pdf File";

        //files to be accepted by the user.
        file.Filter = "Pdf file (*.pdf)|*.pdf|All files (*.*)|*.*";

        // set initial directory of computer system
        file.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

        // set restore directory
        file.RestoreDirectory = true;

        // execute if block when dialog result box click ok button
        if (file.ShowDialog() == DialogResult.OK)
        {
            // store selected file path
            filePath = file.FileName.ToString();
        }

        //file path
        /// use a string array and pass all the pdf for searching
        //String filePath = @"D:\Pranay\Documentation\Working on SSAS.pdf";
        try
        {
            //creating an instance of PdfReader class
            using (PdfReader reader = new PdfReader(filePath))
            {
                //creating an instance of StringBuilder class
                StringBuilder text = new StringBuilder();

                //use loop to specify how many pages to read.
                //I started from 5th page as Piyush told
                for (int i = 5; i <= reader.NumberOfPages; i++)
                {
                    //Read the pdf 
                    text.Append(PdfTextExtractor.GetTextFromPage(reader, i));
                }//end of for(i)

                int k = 4096000;
                //Test whether the string exceeds the 4MB
                if (text.Length < k)
                {
                    //return the string
                    text1 = text.ToString();
                } //end of if
            } //end of using
        } //end try
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Please Do select a pdf file!!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        } //end of catch

        return text1;
} //end of ReadPdfFiles() method
帮帮我

将StringBuilder的长度更改为您指定的长度是达到目的的最简单方法。正如其他答案中所指出的,还有其他方法,但您需要考虑它们的副作用,如字符串处理中的异常或效率低下

    try
    {
        using (PdfReader reader = new PdfReader(filePath))
        {
            StringBuilder text = new StringBuilder();
            .....

            int k = 4096000;

            // If length > limit (k) then truncate 
            if (text.Length > k)
                text.Length = k;

            // Truncate at k or get everything
            text1 = text.ToString();

        } //end of using
   }
   ......

有几种可能性:

您可以阅读文档中的。 您可以使用最大容量初始化stringbuilder。 您可以使用StringBuilder.ToString0,maxlength 您可以使用StringBuilder.ToString.Substring0,maxlength
顺便说一句:4MB=4194304字节

简单地将StringBuilder截断为指定长度的解决方案将无法正确处理。代理项对是表示单个unicode代码点的两个.Net字符的序列;某些汉字就是这样表示的。组合字符序列表示带有变音符号或其他修改标记的字符。因此,如果您的PDF文档可能包含国际字符,并且您应该假设任何用户创建的文档都包含国际字符,那么您需要在StringBuilder长度超过最大长度时或之前,在最后一个抽象字符边界截断StringBuilder

.Net提供了通过中的抽象字符进行枚举的功能,但是它们没有提供类似的工具来通过更一般的字符列表(如StringBuilder)进行枚举。因此,我建议防止StringBuilder超过您的最大长度,而不是在之后截断它:

    public static bool AppendUpToMaximumLength(this StringBuilder sb, string str, int maxLen)
    {
        if (sb == null)
            throw new ArgumentNullException("sb");
        if (str == null)
            str = string.Empty; // Or throw an exception if that's your coding convention.
        var sbLen = sb.Length;
        if (sbLen > maxLen)
            return false;
        if (sbLen + str.Length <= maxLen)
        {
            sb.Append(str);
            return true;
        }
        //http://referencesource.microsoft.com/#mscorlib/system/globalization/textelementenumerator.cs
        var enumerator = StringInfo.GetTextElementEnumerator(str);
        while (enumerator.MoveNext())
        {
            var textElement = enumerator.GetTextElement();
            var elemLen = textElement.Length;
            if (sb.Length + elemLen > maxLen)
                return false;
            sb.Append(textElement);
        }
        return true;
    }

你有什么问题吗?您已经编写了检测字符串长度的代码,因此如果长度太大,只需提供一条错误消息。或者您在将其存储到数据库中时遇到问题?您的数据库访问代码是什么样子的?当达到最大长度时,您希望发生什么?是否使用错误消息中止整个过程?或者写下第一段,然后继续?在这种情况下,更改代码的结构,从循环中调用write方法,而不是返回它!请注意,第2点并不能阻止StringBuilder超出限制。它只是初始缓冲区大小,但如果添加更多数据,它会增加。对于这些大小的字符串,第4点的效率有点低,因为从现有字符串构建新字符串存在构造函数StringBuilderinitialCapacity,maxCapacity,这将导致StringBuilder在长度超过maxCapacity时抛出异常,尽管如文档中所述,长度可能会大于最大容量。第四点仅用于说明如何仅使用字符串方法完成。当然效率很低。好吧,我想你指的是只有容量参数的构造函数。嗨,Steve,定义一个新的长度到一个字符串,它会从末尾修剪字符串吗?string.length是一个只读属性,你不能直接设置一个新值。您需要使用string.Substringstartpos,numberofcharshere我们正在使用StringBuilder ref,因此我认为代码中提供的方法应该作为StringBuilder使用。Length属性是Length{get;set;}