Thursday, February 12, 2015

Build a valid file name

I could not find anything in AX building a true valid file name. That is, just the name of the file itself, not the path.

So I came up with this:
public static Filename buildValidFilename(str  _filename)

    Filename  validFilename;
    str       invalidFileNameChars;

    new InteropPermission(InteropKind::ClrInterop).assert();

    // Remove the characters that .NET defines as invalid
    invalidFileNameChars = new System.String(System.IO.Path::GetInvalidFileNameChars());
    validFilename = System.Text.RegularExpressions.Regex::Replace(_filename, #LeftSquareBracket + invalidFileNameChars + #RightSquareBracket, #emptyString);

    // Remove the characters that .NET doesn't remove
    invalidFileNameChars =  @'"\\/:*?\<>|' + "'";
    validFilename = System.Text.RegularExpressions.Regex::Replace(validFilename, #LeftSquareBracket + invalidFileNameChars + #RightSquareBracket, #emptyString);


    return validFilename;


Evaldas Landauskas said...

Hi Palle,

Have you seen the code in table's BankStatementFormat method validateFieldValue?

You can convert illegal chars from .NET to AX and remove all in AX without hard-coding them.

By the way, you can have an apostrophe in a file name. But you have probably included it for other reasons.


Palle Agermark said...

Thanks Evaldas,

I did have a look at that method, and a couple of similar methods in standard. But they all use the .Net method, and it is, from my point of view, missing especially backslash and forward slash which messes things up for me if used in the file name.

The files are being uploaded to SharePoint, and I had a hunch the apostrophe wouldn't work. But I didn't check it due to ... laziness;-)

mike williams said...

Very helpful, thanks a lot!