Search code examples
c#visual-studio-2010code-access-securitysecurityexception

C# Problem Running WPF


Having some problems in my WPF application using Visual Studio 2010, building in C#. The error coming up at the moment is:

SecurityException was unhandled by user code

The following is the code when I click a button, it checks the size of a text file, and if it has volume or not colors the background of a button called 'ButtonToday'.

private void Button_Click(object sender, RoutedEventArgs e)
{
    //Gets current date and puts it into string.
    string today = DateTime.Now.ToString("yyyy.MM.dd");
    string yesterday = DateTime.Now.AddDays(-1).ToString("yyyy.MM.dd");

    TextBoxToday.Text = "" + today;
    TextBoxYesterday.Text = "" + yesterday;
    FileInfo f = new FileInfo("D:\\Client1\\2011.02.14.log");
    {
        if (f.Length > 0)
            ButtonToday.Background = Brushes.Green;
        else
            ButtonToday.Background = Brushes.Red;
    }
}

Thanks for any help. I am a n00b.


Solution

  • It seems you (or your application) doesn't have the proper permissions open the file. Check and make sure that you can access the file yourself through the filesystem, sounds like you probably can't.

    [edit]You do have permission to read the file, then? Odd. Definitely try the below then, you won't know exactly what's going on until you get more detail from the exception being thrown.[/edit]

    Try this:

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        //Gets current date and puts it into string.
        string today = DateTime.Now.ToString("yyyy.MM.dd");
        string yesterday = DateTime.Now.AddDays(-1).ToString("yyyy.MM.dd");
        TextBoxToday.Text = "" + today;
        TextBoxYesterday.Text = "" + yesterday;
    
         try
         {
             FileInfo f = new FileInfo("D:\\Client1\\2011.02.14.log");
             {
                 if (f.Length > 0)
                     ButtonToday.Background = Brushes.Green;
                 else
                     ButtonToday.Background = Brushes.Red;
             }
         }
         catch ( SecurityException ex )
         {
             ex.Message;
         }
    }
    

    Place a breakpoint over the ex.Message; line, then run your program in debug mode. Hover over the variable ex when you get to it and read the error messages, should give you more information as to what is going on. Hope this helps!