空路径名在c#windows表单中是不合法的

本文关键字:不合法 表单 路径名 c#windows | 更新日期: 2023-09-27 18:29:10

我正在尝试将文档扫描成PDF。在保存文档时扫描文档后,我收到以下错误"空路径名不合法"

private void button2_Click(object sender, EventArgs e)
{
    //  filename = textBox1.Text + "image" + (count++).ToString() + ".jpg";
    _scanner = new ADFScan();
    _scanner.Scanning += new EventHandler<WiaImageEventArgs>(_scanner_Scanning);
    _scanner.ScanComplete += new EventHandler(_scanner_ScanComplete);
    ScanColor selectedColor = (ScanColor)_colors[comboBox1.SelectedIndex];
    int dpi = (int) numericUpDown1.Value;
    _scanner.BeginScan(selectedColor,dpi );
}
void _scanner_ScanComplete(object sender, EventArgs e)
{
    MessageBox.Show("Scan Complete");
    DialogResult dlgresult = MessageBox.Show(
       "Do You Want to Scan More Records ?", 
       "Scan Conformation", MessageBoxButtons.YesNo, 
       MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
    string paths = "E:''Naidu.pdf";
    if (dlgresult == DialogResult.Yes)
    {
        button2.PerformClick();
    }
    else
    {
        Bmec.ScanLibrary.Converters.PdfConverter pdf = new PdfConverter();
        pdf.SaveFrom(item, filename);
        MessageBox.Show("PDF created Successfully");
    }
}

这是我之前创建的类文件,用于将设置保存到pdf文件中

    using System;
   using System.Collections.Generic;
   using System.Drawing;
   using System.Drawing.Imaging;
   using System.IO;
    using System.Linq;
    using System.Text;
    using System.Xml;
    using System.Xml.Linq;
  using Microsoft.Reporting.WinForms;
  namespace Bmec.ScanLibrary.Converters
{
public class PdfConverter
{
    PdfSettings _settings;
    /// <summary>
    /// Default constructor. 
    /// </summary>
    public PdfConverter()
    {
        _settings = new PdfSettings(PdfOrientation.Portrait, PdfSize.Letter);
    }
    /// <summary>
    /// Creates instance for PdfConverter for various convert options. 
    /// </summary>
    /// <param name="settings">Pdf export settings, related to pages sizes.
    /// If settings is null, we use default settings.</param>
    public PdfConverter(PdfSettings settings)
    {
        if (settings == null)
            settings = new PdfSettings(PdfOrientation.Portrait, PdfSize.Letter);
        _settings = settings;
    }
    /// <summary>
    /// Convert to a Stream containing Pdf binary data from a list of images. 
    /// </summary>
    /// <param name="images">List of images.</param>
    /// <exception cref="PdfConverterException">This exception could be thrown if conversion fails.
    /// Usually due to file size is too large.</exception>
    /// <returns>Open stream with position set to 0 (beginning). 
    /// Stream can be read, but needs to be flushed and closed when done.</returns>
    public Stream ConvertFrom(IEnumerable<Bitmap> images)
    {
        Stream resultStream = new MemoryStream();
        Stream outStream = ConvertTo(images, resultStream);
        outStream.Position = 0;
        return outStream;
    }
    /// <summary>
    /// Convert to a Stream containing Pdf binary data from a single image. 
    /// </summary>
    /// <param name="image">Instance of Bitmap image.</param>
    /// <exception cref="PdfConverterException">This exception could be thrown if conversion fails.
    /// Usually due to file size is too large.</exception>
    /// <returns>Open stream with position set to 0 (beginning). 
    /// Stream can be read, but needs to be flushed and closed when done.</returns>
    public Stream ConvertFrom(Bitmap image)
    {
        Stream resultStream = new MemoryStream();
        List<Bitmap> images = new List<Bitmap>();
        images.Add(image);
        Stream outStream = ConvertTo(images, resultStream);
        outStream.Position = 0;
        return outStream;
    }
    /// <summary>
    /// Saves list of images into specified pdf file.
    /// If file already exists, it will be deleted. 
    /// </summary>
    /// <param name="images">List of images.</param>
    /// <param name="pdfFilePath">Pdf file path where images will be saved. If file exists it will be deleted.</param>
    public void SaveFrom(IEnumerable<Bitmap> images, string pdfFilePath)
    {
        if (File.Exists(pdfFilePath)) --------> iam getting exception here
            File.Delete(pdfFilePath);
        Stream resultStream = new FileStream(pdfFilePath, FileMode.OpenOrCreate);
        Stream stream = ConvertTo(images, resultStream);
        stream.Flush();
        stream.Close();
    }
    /// <summary>
    /// Saves image into specified pdf file.
    /// If file already exists, it will be deleted. 
    /// </summary>
    /// <param name="image">Instance of Bitmap image.</param>
    /// <param name="pdfFilePath">Pdf file path where image will be saved. If file exists it will be deleted.</param>
    public void SaveFrom(Bitmap image, string pdfFilePath)
    {
        if (File.Exists(pdfFilePath))
            File.Delete(pdfFilePath);
        if (image == null)
            throw new PdfConverterException("No images to convert!");
        Stream resultStream = new FileStream(pdfFilePath, FileMode.OpenOrCreate);
        List<Bitmap> images = new List<Bitmap>();
        images.Add(image);
        Stream stream = ConvertTo(images, resultStream);
        stream.Flush();
        stream.Close();
    }
    private Stream ConvertTo(IEnumerable<Bitmap> images, Stream resultStream)
    {
        if (images == null && images.Count() == 0)
            throw new PdfConverterException("No images to convert!");
        // creating in-memory report
        XDocument reportXML = CreateRDLC(images);
        Stream stream = new MemoryStream();
        XmlWriter writer = XmlWriter.Create(stream);
        reportXML.Save(writer);
        //disposing
        writer.Flush();
        writer.Close();
        LocalReport report = new LocalReport();
        stream.Position = 0;
        report.LoadReportDefinition(stream);
        //disposing
        stream.Flush();
        stream.Close();
        String mimeType = "";
        String encoding = "";
        String[] streams;
        Warning[] warnings;
        Byte[] renderedBytes;
        StringBuilder deviceInfo = new StringBuilder();
        String fileExtension;
        deviceInfo.Append("<DeviceInfo>");
        deviceInfo.Append("  <OutputFormat>PDF</OutputFormat>");
        deviceInfo.Append("</DeviceInfo>");
        report.Refresh();
        renderedBytes = report.Render("PDF", deviceInfo.ToString(), out mimeType, out encoding, out fileExtension, out streams, out warnings);
        resultStream.Write(renderedBytes, 0, renderedBytes.Length);
        return resultStream;
    }
    private XDocument CreateRDLC(IEnumerable<Bitmap> images)
    {
        int i = 0;
        XNamespace rd = "http://schemas.microsoft.com/SQLServer/reporting/reportdesigner";
        XNamespace xmlns = "http://schemas.microsoft.com/sqlserver/reporting/2005/01/reportdefinition";
        XDocument doc = new XDocument(
            new XDeclaration("1.0", "utf-8", "no"),
            new XElement(xmlns + "Report",
                new XAttribute(XNamespace.Xmlns + "rd", "http://schemas.microsoft.com/SQLServer/reporting/reportdesigner"),
                new XElement(xmlns + "InteractiveHeight", _settings.HeightLabel),
                new XElement(xmlns + "InteractiveWidth", _settings.WidthLabel),
                new XElement(xmlns + "RightMargin", _settings.RightMarginLabel),
                new XElement(xmlns + "LeftMargin", _settings.LeftMarginLabel),
                new XElement(xmlns + "BottomMargin", _settings.BottomMarginLabel),
                new XElement(xmlns + "TopMargin", _settings.TopMarginLabel),
                new XElement(xmlns + "Width", _settings.BodyWidthLabel),
                new XElement(rd + "SnapToGrid", "true"),
                new XElement(rd + "DrawGrid", "true"),
                new XElement(rd + "ReportId", (new Guid()).ToString()),
                new XElement(xmlns + "EmbeddedImages",
                    from Bitmap image in images
                    select new XElement(xmlns + "EmbeddedImage",
                        new XAttribute("Name", "i" + image.GetHashCode().ToString()),
                        new XElement(xmlns + "MIMEType", "image/jpeg"),
                        new XElement(xmlns + "ImageData", BitmapToByte(image)))
                    ),
                new XElement(xmlns + "Body",
                    new XElement(xmlns + "ReportItems",
                        from Bitmap image in images
                        select
                            new XElement(xmlns + "Image",
                                new XAttribute("Name", "ImageName" + image.GetHashCode().ToString()),
                                new XElement(xmlns + "Sizing", "FitProportional"),
                                new XElement(xmlns + "Height", _settings.BodyHeightLabel),
                                new XElement(xmlns + "Top", ((i++) * _settings.BodyHeight).ToString() + "in"),
                                new XElement(xmlns + "MIMEType", "image/jpeg"),
                                new XElement(xmlns + "Source", "Embedded"),
                                new XElement(xmlns + "Style"),
                                new XElement(xmlns + "ZIndex", 1),
                                new XElement(xmlns + "Value", "i" + image.GetHashCode().ToString()))
                    ),
                    new XElement(xmlns + "Height", _settings.BodyHeightLabel)
                ),
                new XElement(xmlns + "Language", "en-US")
            )
        );
        return doc;
    }
    private String BitmapToByte(Bitmap image)
    {
        String result = String.Empty;
        // the file size is limited here to .NET 128 MB per array per ApplicationDomain. 
        // so if image file is close or greater than 128 MB this will fail. 
        try
        {
            Stream str = new MemoryStream();
            image.Save(str, ImageFormat.Jpeg);
            Byte[] output = new Byte[str.Length];
            str.Position = 0;
            str.Read(output, 0, (int)str.Length);
            result = Convert.ToBase64String(output, Base64FormattingOptions.None);
            str.Flush();
            str.Close();
        }
        catch (OutOfMemoryException ex)
        {
            throw new PdfConverterException(ex.Message, ex, "The file size is too large. It is limited to 128 MB. Try smaller image.");
        }
        catch (Exception ex)
        {
            throw new PdfConverterException(ex.Message, ex);
        }
        return result;
    }
}

}

空路径名在c#windows表单中是不合法的

  filename = textBox1.Text + "image" + (count++).ToString() + ".jpg";

那一行似乎被注释掉了,可能是文件名为空吗?

设置filename的行被注释掉,而不是设置paths变量,但re not using the路径是variable in-pdf。保存自(项,文件名);`。这可能就是您出现错误的原因。