Uchiha Itachi
Uchiha Itachi

Reputation: 1271

Receiving IOException

I'm getting the IOException Error when I try this, and I'm not sure what I'm doing wrong:

enter image description here

This is my code:

FileStream fStream = new FileStream(PDFFilePath(), FileMode.CreateNew, FileAccess.ReadWrite);

Where

private string PDFFilePath()
    {
        m_sFilePath = "C:/Pictures/";
        return m_sFilePath;
    }

What am I missing?

I'm using this FileStream to save PDF documents using the Pdf.Select NuGet. It uses a method:

PdfDocument.Save(Stream stream);

Upvotes: 0

Views: 61

Answers (2)

You have several problems here.

First, if you use a path like C:\Pictures\, it'll complain about the trailing \.

Secondly, you need to specify an actual file here, not just a directory. It makes no sense to just specify a directory (rather than a file) in this case - that's why it's called a File Stream and not a Directory Stream. I suggest using Path.Combine for this. Also, if you're just trying to move an already-existing file to this directory, you should do File.Move rather than using a FileStream.

Third, you only want to use FileMode.CreateNew if there's no possibility that the file already exists in the destination folder; if it does exist, this will throw an exception.

Fourth, it's a bad practice to hardcode paths like this. You usually want to get the path from a configuration file and make sure that the Pictures directory does, in fact, exist before you try to do this operation; otherwise it may fail when you deploy it to another machine.

Fifth, the PDFFilePath method seems rather pointless in this case - you can do the same thing with a string constant or creating a readonly string in the constructor.

Upvotes: 1

Mat
Mat

Reputation: 1500

I think you should be specifying your path this way:

private string PDFFilePath(string filename)
{
    m_sFilePath = @"C:\Pictures\" + filename;
    return m_sFilePath;
}

Like @Reisclef said, you have to provide a file path, not a directory. Since you're using FileMode.CreateNew, it has to be a new file, so you might also want to use File.Exists(m_sFilePath) before returning.

Upvotes: 1

Related Questions