Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fixing CA2122 with Process.Start

In an application we can output a report as a csv file and load it up similar to the following code:

Process.Start("C:\MyReport.csv") ' Not real path 

When running code analysis it produces the following error:

CA2122 Do not indirectly expose methods with link demands 'Form.Function(Definition)' calls into 'Process.Start(String)' which has a LinkDemand. By making this call, 'Process.Start(String)' is indirectly exposed to user code

I have seen somewhere to mark the assembly with the SecurityTransparentAttribute, does this just suppress the message? If so this is not what I would like. Is there another way of opening the file that would circumvent this message without suppressing it? I would ideally like to avoid Excel automation if I can as Excel is not used anywhere else at the moment.

Ideas?

like image 870
Stuart Blackler Avatar asked Jan 27 '26 18:01

Stuart Blackler


1 Answers

I stumbled upon the same issue today and thought the following answer would be useful for others so thought to write it.

So basically, my code was to open up a given directory path in explorer, as shown below

public static void OpenDirectoryPath(string directoryPath)
{
    if (Directory.Exists(directoryPath))
    {
        Process.Start(directoryPath);
    }
}

The above code produced the following error

CA2122 : Microsoft.Security : 'Helper.OpenDirectoryPath(string)' calls into 'Process.Start(string)' which has a LinkDemand. By making this call, 'Process.Start(string)' is indirectly exposed to user code. Review the following call stack that might expose a way to circumvent security protection:

The question to ask is, do you really want this method to be public. In my case, the answer was "No". Changing the method to internal resolved the problem.

internal static void OpenDirectoryPath(string directoryPath)
{
    if (Directory.Exists(directoryPath))
    {
        Process.Start(directoryPath);
    }
}
like image 57
Hamid Shahid Avatar answered Jan 30 '26 08:01

Hamid Shahid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!