2

I'd like the line to execute when running within Visual Studio but not when the exe is running stand alone.

Thanks.

AntonyW
  • 2,284
  • 16
  • 21
AAsk
  • 1,431
  • 4
  • 17
  • 25

6 Answers6

8

Do you mean when a debugger is attached? If so, you could do something like this:

#if DEBUG
if (Debugger.IsAttached)
{
    //Your code here
}
#endif

This will only run when the debugger is attached, such as running with F5. Double clicking it or using Ctrl+F5 won't cause the if statement to be hit. It's also wrapped in a conditional so then when you compile to release the code is not even there.

vcsjones
  • 138,677
  • 31
  • 291
  • 286
5

You could use the build flags

#if DEBUG
      //do something in here
#endif

And then when you build in release those things won't happen.

Fourth
  • 9,163
  • 1
  • 23
  • 28
2

You can use ConditionalAttribute. Put the code you want to execute conditionally in a method, and mark the method with [Conditional("DEBUG")]. The method and the call to it will only be compiled when the DEBUG constant is set.

Tom W
  • 5,108
  • 4
  • 30
  • 52
1

Try this thread: How to tell if .NET code is being run by Visual Studio designer

Community
  • 1
  • 1
E.J. Brennan
  • 45,870
  • 7
  • 88
  • 116
0

I think this code may help:

[Conditional("DEBUG")]
private void DEBUG_Execute() 
{ 
    if (Debugger.IsAttached)
    { 
        //todo:  execute line when running within VS
    } 
} 
ArekBee
  • 311
  • 2
  • 6
-1

You can check the Application.startuppath

If you are in Debugging, that means bin/Debug folders are present otherwise you are running the exe. In this way you can formulate the code.

Pankaj
  • 9,749
  • 32
  • 139
  • 283
  • That seems very fragile, and for web applications, there is no Debug / Release directory. Just bin. – vcsjones May 23 '11 at 13:40
  • Yes. Thanks for the reply. But the OP did not mentioned ASP.net and I also have understood to use #if DEBUG if (Debugger.IsAttached) { //Your code here } #endif because of less computations. In my case I was evaluating the Application.startuppath – Pankaj May 23 '11 at 13:42
  • Even in other project types, this `Debug` path is not guaranteed to be present, and from my experience scarcely is with professional project build plans. In short, this is an awful idea. – Grant Thomas May 23 '11 at 13:48