【问题标题】:How to restrict a content of string to less than 4MB and save that string in DB using C#如何将字符串内容限制为小于 4MB 并使用 C# 将该字符串保存在 DB 中
【发布时间】:2014-07-12 07:35:30
【问题描述】:

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

但现在我需要检查字符串是否超过 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

帮帮我吧!

【问题讨论】:

  • 您遇到了什么问题?您已经编写了检测字符串长度的代码,因此如果长度过大,您只需提供错误消息。或者您在将其存储在数据库中时遇到问题?您的数据库访问代码是什么样的?
  • 你想在最大值时发生什么。长度达到?中止整个过程并显示错误消息?或者也许写出第一块然后继续?在这种情况下,请更改代码的结构以从循环中调用 write 方法,而不是返回它!

标签: c# string pdf itextsharp


【解决方案1】:

有几种可能:

  1. 您可以阅读StringBuilder class 的文档。
  2. 您可以使用最大容量来初始化您的字符串生成器。
  3. 您可以使用 StringBuilder.ToString(0, maxlength)
  4. 您可以使用 StringBuilder.ToString().Substring(0, maxlength)

顺便说一句:4MB = 4194304 字节

【讨论】:

  • 两个注意事项,第 2 点不会阻止 StringBuilder 超出限制。 (这只是初始缓冲区大小,但如果添加更多数据,它会增加)。第 4 点对于这些大小的字符串有点低效,因为从现有字符串构建一个新字符串
  • 有一个构造函数 StringBuilder(initialCapacity, maxCapacity) 如果长度超过 maxCapacity 将导致 StringBuilder 抛出异常(尽管如文档中所述,即使那样,长度也可能大于maxCapacity) 第 4 点仅用于展示如何仅使用字符串方法来完成。当然效率很低。
  • 好吧,我以为你指的是只有容量参数的构造函数。
【解决方案2】:

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

    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
   }
   ......

【讨论】:

  • 嗨史蒂夫,定义一个新的字符串长度,它会从结尾修剪字符串吗?
  • String.Length 是只读属性,不能直接设置新值。您需要使用 string.Substring(startpos, numberofchars)
  • 这里我们使用 StringBuilder ref 所以我认为代码中提供的方法应该作为 StringBuilder.Length 属性是 Length { get;放; }
【解决方案3】:

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

.Net 提供了utilities 用于枚举string 中的抽象字符,但是它们没有提供类似的工具来枚举更通用的字符列表,例如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;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-05
    相关资源
    最近更新 更多