12
votes

I have a small .NET app that I'm running under Windows 2008 Server via the Task Scheduler. This application needs to open an excel file and then save it as csv. The task fails when I try to open the workbook. If I run it manually without the task scheduler running it, the app works fine.

I have it set to "Run with highest privileges" and have "Run weather user is logged on or not" checked.

My guess is that this process needs to interact with the desktop similar to check the "interact with desktop" flag on a service. But I have been unable to find a similar thing for scheduled tasks.

Here is code that is failing: (it fails on the workbook.open call)

public static void ConvertExcelToCsv(string source, string destination)
{
    if (File.Exists(destination)) File.Delete(destination);

    Application xl = new Application();

    try
    {
        Workbook workbook = xl.Workbooks.Open(source, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
        Worksheet ws = (Worksheet)workbook.Sheets[1];
        ws.SaveAs(destination, XlFileFormat.xlCSV, Type.Missing, Type.Missing, false, false, Type.Missing, Type.Missing, Type.Missing,true);

        Marshal.ReleaseComObject(ws);
    }
    finally
    {
        xl.DisplayAlerts = false;
        xl.Quit();

        Marshal.ReleaseComObject(xl);                
    }

}
2

2 Answers

11
votes

I've had problems automating Office from a Windows Service under Windows Server 2008, even though that works fine under Windows Server 2003. The problem also occurs at the Open call, so it may be the same problem.

I tried following the advice given by H Ogawa in this MSDN thread, and it seemed to work. It's bizarre, but kudos to Mr. Ogawa for discovering it.

Summary of the 'Ogawa Hack': create a desktop folder for the system profile, as either

C:\Windows\SysWOW64\config\systemprofile\Desktop, or

C:\Windows\System32\config\systemprofile\Desktop

...depending on whether you have 64-bit Windows.

Also, the folder needs write permission for whatever user is "driving" Office.

[Edit: corrected link URL]

0
votes

This got me so crazy, i was trying to launch a script that converts DOC to PDF and that worked perfectly when executed throug Task Scheduler on Windows 10 but not on Windows Server 2016. This did the trick! KUDOS MR. OGAWA!