创建excel文件时出现UnauthorizedAccessException

时间:2014-10-14 21:16:21

标签: c# wpf excel exception

这个代码在我的Windows 7机器上运行得很好,但现在在Windows 8上它在System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Movie Database.xls");行崩溃了

Movie_DataGrid.SelectAllCells();
Movie_DataGrid.ClipboardCopyMode = DataGridClipboardCopyMode.ExcludeHeader;
ApplicationCommands.Copy.Execute(null, Movie_DataGrid);
String resultat = (string)Clipboard.GetData(DataFormats.CommaSeparatedValue);
String result = (string)Clipboard.GetData(DataFormats.Text);
FileStream xls = null;
try
{
    try
    {
        xls = new FileStream(@"C:\Movie Database.xls", FileMode.Open, FileAccess.ReadWrite);

    }
    catch (Exception )
    {
        IsProcessOpen("EXCEL");
        xls = new FileStream(@"C:\Movie Database.xls", FileMode.Open, FileAccess.ReadWrite);
    }
}
catch (FileNotFoundException )
{
    MessageBox.Show("File was not found. Creating File");
    System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Movie Database.xls");
    file.WriteLine(result.Replace(',', ' '));
    file.Close();
}
finally
{
    if (xls != null)
    {
        System.IO.StreamWriter file = new System.IO.StreamWriter(xls);
        file.WriteLine(result.Replace(',', ' '));
        file.Close();
    }
}

我没有创建名为Movie Database.xls的文件,因此它应该创建文件并将数据写入其中。我不知道它是Windows 8还是我有excel 2013这一事实阻止我访问。关于例外的任何建议。我再次使用excel 2010的Windows 7盒子上的代码就好了,所以我知道它有效。

0 个答案:

没有答案