Visual Studio clears output file at end of debugging - c#

I am experiencing a weird behaviour from Visual Studio 2013. I've got a C# program which writes to the standard output, let's say
using System;
using System.Threading;
namespace CsSandbox
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello world!");
Thread.Sleep(10000);
}
}
}
In the Debug tab of the project's properties I have redirected the output to a file, like this:
If I open the file within those 10s when my application is still running, the file does contain "Hello world!". However, as soon as the program exits, the file is cleared. This does not happen when I run the program from the command line.
Is there a rationale why Visual Studio does it? Is there a way to bypass this behaviour?

I believe this is due to the way Visual Studio hosts your application, in order to reduce startup time when debugging.
What happens is that your application (Program.exe) will actually be hosted in another process (Program.vshost.exe), which is started with the same command line arguments. When your application ends, this process is immediately restarted. You should be able to see this within Task Manager - look in the details tab so you can see the PID of the processes, and run your app - you'll see one Program.vshost.exe instance which ends when your app finishes, and another one come up immediately. That's then overwriting your output file.
One fix for this is to give your application a command line argument for the file to write to - and open that file within your Main method. You won't get there until you start running the app again.
Another option would be to simply stop using the hosting process - in the Debug part of your project properties, at the bottom you should see a checkbox for "Enable the Visual Studio hosting process". Uncheck this and I think your problem will go away - but it'll take longer to start debugging.
See this blog post for more information about the hosting process.

Related

Console immediately closes with CTRL+F5

In Visual Studio 2017, I'm using C# to create a basic hello world application.
CTRL+F5 (Start without debugging) immediately shuts down without showing the output.
I've followed this solution the second most upvoted answer
EDIT: Apparently this solution doesn't apply to C#
I've also tried resetting my settings and uninstalling visual studio. I don't want to add breakpoints or ReadLine.
Bottom line, I just want my program to not exit on CTRL+F5.
using System;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("hello world");
}
}
}
Did you create this using the console app template? If not, try doing that.
You can check that it's set correctly by making sure that the output type (properties --> Application --> Output type) is set to 'Console Application' for this to work when pressing CTRL + F5
in a console app you need some sort of wait after you print to the screen or the app will exit. try adding Console.ReadLine(); it will then wait until you press enter to exit.
EDIT:
if you don't want to do that then run it from a command prompt to avoid the auto close behavior that Visual Studio adds.
Jay pointed out in a comment that maybe I used the wrong template. I don't know what template I used before, but I remade the application using the Console template and it works now.
Make sure that command line arguments have one line only. Check your start-up project Properties | Debug | Start options | Command line arguments.

C# Console Application build but not launch application

I have a simple Console Application write with C-Sharp language (Visual Studio 2013):
using System;
using System.Collections.Generic;
using System.Text;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World");
Console.ReadKey();
}
}
}
When I press F5 or click Start button, my project was built, but not launch.
Sometime, Ouput windows says:
Error 12 Could not copy "obj\Debug\HelloWorld.exe" to "bin\Debug\HelloWorld.exe". Exceeded retry count of 10. Failed.
Error 13 Unable to copy file "obj\Debug\HelloWorld.exe" to "bin\Debug\HelloWorld.exe". The process cannot access the file 'bin\Debug\HelloWorld.exe' because it is being used by another process.
but when I write Windows Form Application, my project was built and launch normally ???
Why? and How to solve this problem ?
This is most likely due to windows keeping the process open. Your only option is to try and kill all processes of your app in task manager->processes.
The next thing to try is to simply change the build from debug to release, this should build another executable in the release folder as opposed to debug. By no means is this a silver bullet but, hopefully a sufficient workaround.
Before you try the release build, attempt to try and fix the problem. I've seen windows moan at just having my debug folder open and my exe selected because I suspect the thumbnail was being displayed thus being "used" in windows etc.
I found reason and solve for my problem.
I tried to restart Application Experience Service and the problem was solved.
Please restart yor Visual Studio and then try again. It will work and delete your bin/debug folder again.
I have faced with this issue.
That happeneds when an instance of software is running whether by visual studio or by your self
solution :
you should find your application name in the processes of task manager
your's is :
HelloWorld.exe
select that and click on the end task button
now you can start debugging and running you'r app.
at least worked for me.

Can't break in global.asax / Application_Start

I got a break point on the first line of Application_Start(), but Visual Studio wont break on it.
Visual Studio have attached itself to the IIS working process:
Auto-attach to process '[2092] w3wp.exe' on machine 'SRD00510' succeeded.
My breakpoint in the home controller do work.
update
I've tried:
iisreset
restarted visual studio
Rebooted.
Tried to reinstall aspnet (aspnet_regiis -i)
Reading your question, I assume you are using IIS for debugging, not Visual Studio Development Server.
In this case, debugging application start is tricky, because it is only called once when the application pool is started or recycled. When Visual Studio attaches to the process, Application_Start has already been running.
The trick is to make the application pool recycle without killing the process you are attached to.
Do the following:
In Visual Studio (must be run as Administrator) set your breakpoint in
global.asax.cs and start debugging as usual (F5). The page opens in
your web browser, but the breakpoint isn't hit.
Now the trick: With a text editor, open web.config from where it is
served by IIS, change it (e.g. enter a blank line somewhere) and
save it. In contrast to recycling the application pool in IIS, this
lets the application pool recycle (and thus running through
Application_Start in global.asax.cs the next time the web site is
called) without killing the process you are attached to.
In your web browser, reload the page. The breakpoint should be hit now!
That works for me (IIS 7.5, VS2015).
Place this line in your Application_Start().
Debugger.Break();
This will present you with a dialog which will allow you to select a debugger. You might need to restart the application pool.
Application_Start() only runs once, when the application starts. A few things that restart the application are:
web.config changes
recycling the worker process - you can do this in IIS Manager or by running iisreset at the command line.
My solution is to switch to using the 'Visual Studio Development Server' to deal with the application class (Global.asax) issues. When done I switch back to IIS.
I assume you're loading the application by clicking the "debug" button in Visual Studio? That's what I'm doing (in VS 2012) and seeing similar problems. Pressing that button the first time starts the application and correctly hits the breakpoint. But it seems like after I stop debugging the application itself keeps going. So, future attempts to debug just attach to the existing process.
There's a "restart" button next to the "stop debugging" button, so I'd assume clicking that at least would change things.
The debugging app does not show up in IIS manager, so I can't stop it there. Likewise, iisreset doesn't catch it either.
Only thing I've figured out so far is to change a line of code, thereby forcing visual studio to trigger a build and then it kills the existing proc and starts over. Kind of annoying if I just want to step through there multiple times.
I don't consider this a suitable "answer", but it might be a helpful workaround for you until somebody does come in with a real answer.
I've got around this problem before by doing this:
Run a clean on my solution (Right click the solution node and click clean)
Close solution
File -> Exit on visual studio
If you have multiple instances of visual studio running then exit out of all instances. Ensure "devenv.exe" is not listed in the processes in task manager
Delete the user options file (.suo), usually in the same directory as your solution (.sln) file
Recycle IIS worker process or if using the development server, kill that process
Now open your solution and give it a shot. (keep your fingers crossed :))
Whenever you run an application for the first time, or say start an application, there is an ASP.Net Development Server - Port [port number] that starts,
Application_Start() runs once in the course of an application.
If you want the break point to be reached , you have to stop the ASP.Net Development Server Port and run your application again.
if [2092] w3wp.exe is a service that you made, try this :
stop service -> rebuild service project -> start rebuilt service -> try to debug
If using IISEXPRESS is not an option, as #David Perlman mentions, I would go for a Logger. Log4Net or NLog are both good. It's good to have a logger in the longrun, for instance in production environments.
namespace DataService
{
using NLog;
public class Global : System.Web.HttpApplication
{
private Logger log;
protected void Application_Start(object sender, EventArgs e)
{
LogManager.LoadConfiguration("nlog.config");
log = LogManager.GetCurrentClassLogger();
log.Error($"Read this line in the log specified in nlog.config");
}

How do I debug a filter program in Visual Studio 2010?

I'm trying to debug a filter program written as a C# console application. The usage of the program would be something like (executed from cmd.exe):
C:\MyDir\>type inputfile.txt | myfilter.exe
I have tried the obvious: Attach to the cmd.exe process and set a break point in my Main function. Software runs, Symbols aren't loaded, Debugger doesn't break into, Developer unhappy.
In the project properties, under Debug, it is possible to set Command line arguments. I don't have no stinking command line arguments. I want to have a file piped in to STDIN. How hard can that be?
Nevermind, I'm just not thinking today...
You just need to add a Debugger.Launch() call to your Main method:
static void Main(string[] args)
{
Debugger.Launch();
// rest of your program goes here
}
And Windows will be nice and let you debug your program. I knew this - this is how to debug custom actions in setup projects...
You need to attach to myfilter.exe, the fact that it is launched from the command line is not important. However if you have the project open in visual studio you just start debugging and it will attach automatically. Yes you can pass in command line arguments, either start the exe with the relevant arguments and then atatch or do it straight from visual studio go to the console application project properties and there is a command line arguments box in the debug section.

How does VS compile console applications to show "Press any key to continue"?

When I develop a C# console application (which will run on a server) and I run it using Visual Studio, I get a "Press any key to continue" message before the program terminates.
However, when I compile the very same C# code file manually using CSC, my program doesn't show that message and it terminates immediately after finishing its logic.
Does anyone know how I can make the same feature when compiling the code without using VS and WITHOUT changing the C# code any adding a ReadLine()?
UPDATE : The same message used to appear when I learned C#, I used to use TextPad with CSC, and that message used to appear without adding any Write(Line)/Read(Line) callings
It's nothing to do with the compiler - if you press F5 to debug it rather than Ctrl-F5 to run without debugging, then VS doesn't show the prompt. This is presumably so that you don't miss whatever output it's producing.
In order to do this, Visual Studio runs cmd.exe telling it to run your executable and then pause:
"C:\WINDOWS\system32\cmd.exe" /c ""...\ConsoleApplication1.exe" & pause"
It probably doesn't do it when you debug as it's a bit harder to get the process ID of a child of a child process.
To add a similar option to your program, either use a command line switch to tell the application itself to pause, or use a batch file to run it then pause, or use a shortcut with them cmd.exe /c.
That's not possible. The prompt to press any key is generated by Visual Studio when running a console app. It's not part of your program.
The only way is by using Console.Read() in your code
UPDATE: concerning your remark on using TextPad: I'm not familiar with TextPad, but I wouldn't be surprised if TextPad did the same thing as Visual Studio when running a console app.
You could do this...
static void Main(string[] args)
{
#if DEBUG
Console.Read();
#endif
}
That way the program will not wait for the console input when you build your application as a 'Release'.
You could write a batch script that runs the exe for you and prompts the user to press a key.
The batch script would look something like this:
echo off
YourApp.exe
pause
You could do this, if you want the same functionality when debugging.
if (Debugger.IsAttached)
{
Console.WriteLine("Press any key to continue . . . ");
Console.ReadKey(true);
}
This behavior has nothing to do with the compiler you are using. When you compile with Visual Studio, running the executable outside of Visual Studio actually will perform exactly the same as when you compile with CSC on the command line. Visual Studio (and TextPad) is adding the logic to add the "Press any key to continue" message on the console.
If you want your application to stay open, you will need to do something like Console.ReadLine() to block execution so that your application does not complete its execution.
The question is why would you want to have this behaviour? The Press any key to continue feature is there so that you can see the output of your application. If on the other hand you build your code and run it from a command prompt (console), this will not close when the application finishes, so you can see the output.
As noted above, the Press any key to continue is a feature of the IDE and not related to the code you are writing. The purpose of that feature is to allow you to see the output of you console application.

Categories

Resources