OiRc
OiRc

Reputation: 1622

Problem with file document attachment in Dynamics 365 Operations

I have a batch process that generates PDF document. But when I create it, I find it corrupted.

Any suggestions for this code?

public boolean PDFProcess()
{
    List                PDFFiles;
    ListEnumerator      PDFEnumerator;
    boolean             errors;
    filename            _from,_to,_temp, _name, _ext;
    container           _split;
    Bindata             _bin;
    DocuRef             docuref;
    custTable           custTable;
    DocuActionArchive   DocuActionArchive;
    System.IO.MemoryStream stream;
    System.IO.StreamWriter write;
    PDFFiles = VE005FilesTools::GetlistOfFiles(VEParameters.VE005Path2Read,VEParameters.VE005FileNameDocumentFilter);
    PDFEnumerator = PDFFiles.getEnumerator();
    while(PDFEnumerator.moveNext())
    {
        _from = PDFEnumerator.current();
        custTable = this.DecodePDF(_from);

        if (custTable)
        {
            _split = fileNameSplit(_from);
            _name = conPeek(_split,2);
            _ext = conPeek(_split,3);
            stream = new System.IO.MemoryStream();
            writer = new System.IO.StreamWriter(stream);
            writer.Write(_name);
            writer.Flush();
            docuref = DocumentManagement::attachFileToCommon(CustTable, VEParameters.VE005DocuTypeId, stream, _name+_ext, 'PDF', _name+_ext);


            if (this.move(_from,VEParameters.VE005Path2Backup))
            {
                errors = true;
            }
        }
        else
        {
            if (this.move(_from,VEParameters.VE005Path2Errors))
            {
                errors = true;
            }
        }
    }
    return errors;
}

Upvotes: 1

Views: 1786

Answers (1)

DAXaholic
DAXaholic

Reputation: 35398

At first glance it simply seems that you are not reading and writing the file's contents to the MemoryStream but just the name

writer.Write(_name);

That's why your PDF is probably corrupted (and pretty small as well :))

Either write all bytes of the file to the MemoryStream, i.e. replace the line above with something like this:

writer.Write(System.IO.File::ReadAllBytes(_from));

However, the better way if possible would be to directly use a file stream and thus bypassing the overhead of the MemoryStream:

using (var stream = System.IO.File::OpenRead(_from))
{
    docuref = DocumentManagement::attachFileToCommon(CustTable, VEParameters.VE005DocuTypeId, stream, _name+_ext, 'PDF', _name+_ext);
}

I do not have access to a dev environment right now so I couldn't test them yet. Let me know if it worked (I'll test it anyway once I have a chance to do it).

Upvotes: 1

Related Questions