views:

678

answers:

2

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);                
    }

}
+1  A: 

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]

Gary McGill
It works! Thats crazy, I would never have found that thank you. Also the link above is incorrect, you can find the article described here: http://social.msdn.microsoft.com/Forums/en-US/innovateonoffice/thread/b81a3c4e-62db-488b-af06-44421818ef91
Kelly
A: 

You may also need to disable UAC for the user account driving the Office automation on the server - that's what was the final kink for me.

Tim Ellis