I'm trainning in C# alone for this moment, and encounter my first problem.
I use VSCode as IDE.
What I Am Try To Do
Create two functions, the first, data like name and return it. the second return full name. All in one in a class.
What I Do From Here
using System
namespace Helloworld
{
class Program
{
static void Main(string[] args)
{
Program p = new Program();
Console.WriteLine(p.getFullName())
}
public string getName(string message)
{
string? name;
do
{
Console.WriteLine(message);
name = Console.ReadLine();
}
while (string.IsNullOrEmpty(firstName)); // For avoid null or empty string, I'm not found another solution.
return name;
}
public string getFullName()
{
const string firstNameMessage = "Enter your first name: ";
const string lastNameMessage = "Enter yout last name: ";
string result = $"{getName(firstNameMessage)} {getName(lastNameMessage)}"
return result;
}
}
}
I Have Encountered Any Problems
1 - When I launch the command dotnet run, my program follow instructions while the first Console.WriteLine. When I type an random name in VSCode's Debug Console. Nothing happens...
My questions: Does this problem come my code ? Am I using an unsuitable IDE ? Or Am I not working with the good VSCode's Tools ?
2 - When I want restart or build I have a message like The process cannot access the file C:\Users\Username\ Documents\Work\learningCSharp\bin\Debug\net6.0\learningCSharp.dll' because it is being used by another process.
My question: How I kill process which use my DLL file ?
I solve all my problem finally alone. I read here the solution.
I'm posting the solution anyway.
in your launch.json replace "console": "internalConsole" by "console": "integratedTerminal.
If you are senior in C#, Can you tell us if is it same for all IDEs ?
Related
I have no coding experience but have been trying to fix a broken program many years ago. I've been fumbling through fixing things but have stumbled upon a piece that I can't fix. From what I've gathered you get Alexa to append a Dropbox file and the program reads that file looking for the change and, depending on what it is, executes a certain command based on a customizable list in an XML document.
I've gotten this to work about five times in the hundred of attempts I've done, every other time it will crash and Visual Studio gives me: "System.IO.IOException: 'The process cannot access the file 'C:\Users\\"User"\Dropbox\controlcomputer\controlfile.txt' because it is being used by another process.'"
This is the file that Dropbox appends and this only happens when I append the file, otherwise, the program works fine and I can navigate it.
I believe this is the code that handles this as this is the only mention of StreamReader in all of the code:
public static void launchTaskControlFile(string path)
{
int num = 0;
StreamReader streamReader = new StreamReader(path);
string str = "";
while (true)
{
string str1 = streamReader.ReadLine();
string str2 = str1;
if (str1 == null)
{
break;
}
str = str2.TrimStart(new char[] { '#' });
num++;
}
streamReader.Close();
if (str.Contains("Google"))
{
MainWindow.googleSearch(str);
}
else if (str.Contains("LockDown") && Settings.Default.lockdownEnabled)
{
MainWindow.executeLock();
}
else if (str.Contains("Shutdown") && Settings.Default.shutdownEnabled)
{
MainWindow.executeShutdown();
}
else if (str.Contains("Restart") && Settings.Default.restartEnabled)
{
MainWindow.executeRestart();
}
else if (!str.Contains("Password"))
{
MainWindow.launchApplication(str);
}
else
{
SendKeys.SendWait(" ");
Thread.Sleep(500);
string str3 = "potato";
for (int i = 0; i < str3.Length; i++)
{
SendKeys.SendWait(str3[i].ToString());
}
}
Console.ReadLine();
}
I've searched online but have no idea how I could apply anything I've found to this. Once again before working on this I have no coding experience so act like you're talking to a toddler.
Sorry if anything I added here is unnecessary I'm just trying to be thorough. Any help would be appreciated.
I set up a try delay pattern like Adriano Repetti said and it seems to be working, however doing that flat out would only cause it to not crash so I had to add a loop around it and set the loop to stop when a variable hit 1, which happened whenever any command types are triggered. This takes it out of the loop and sets the integer back to 0, triggering the loop again. That seems to be working now.
I would like to have commands within the executable itself for example:
shorten http://stackoverflow.com/
and the url will be parsed as an argument, if I set it to return the argument, it should return me http://stackoverflow.com/
Another example is
foo bar
and it will check what is the main command which is foo and subcommands under it, which is bar and will execute the command.
This should be done within the executable and not calling the executable in the directory. I would like to have multiple custom commands within the executable and not create one for each command.
I understand how to have arguments if each command was an executable, but I would like a few commands and subcommands within 1 executable. Is this possible?
EDIT:
This is what I want:
static void Main(string[] args)
{
for (int i = 0; i < args.Length; i++)
{
if (args[i] == "short")
{
Console.WriteLine(args[i + 1]);
}
}
Console.Read();
}
which will return me the arguments of short. So if I type short link it will return me link.
However this will only work if I call the executable through the command line like C:\Path\ConsoleApplication1.exe not if I open up the application and type short link, which will not return me anything and close.
How do I make it work when I open up the application and type it in?
You can use Console.ReadLine:
var input = Console.ReadLine();
To get command and argument(s) use String.Split :
var command = input.Split()[0];
var argument1 = input.Split()[1];
etc.
I have a weird problem. I want to write the visible textBox.Text to an "ini" file on FormClosing (right before the form shuts down), so I double clicked that event under the main form's Properties panel and filled the associated function as follows:
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
// store the whole content in a string
string settingsContent = File.ReadAllText(settingsPath + "CBSettings");
// replace a name with another name, which truly exists in the ini file
settingsContent.Replace(userName, userNameBox.Text);
// write and save the altered content back to the ini file
// settingsPath looks like this #"C:\pathToSettings\settingsFolder\"
File.WriteAllText(settingsPath + "CBSettings", settingsContent);
}
The form starts up without a problem, but it won't quit by clicking the x button. It only closes correctly when I comment the File.WriteAllText line out. If I just stop debugging, the files content doesn't change either.
EDIT :
The actual problem was the function which I used to find and return the userName from the ini file:
public static string GetTextAfterTextFromTextfile(string path, string file, string fileExtension, string textToLookFor)
{
string stringHolder;
StreamReader sr = File.OpenText(path + file + fileExtension);
while((stringHolder = sr.ReadLine()) != null)
{
if(stringHolder.Contains(textToLookFor))
{
return stringHolder.Replace(textToLookFor, "");
}
}
sr.Close();
return "Nothing found";
}
The content of the ini file:
User Name = SomeName
Bot Name = SomeName
I copied the above function from stackoverflow. I was sure that it worked because it captured 'SomeName' just as I wanted. Now I use another function (also from stackoverflow), that searches the ini file for 'User Name = ' and returns the text that comes right after it.
public static string GetTextAfterTextFromTextfile(string path, string textToSkip)
{
string str = File.ReadAllText(path);
string result = str.Substring(str.IndexOf(textToSkip) + textToSkip.Length);
return result;
}
The problem is, that it returns
SomeNameBot Name = SomeName
Any hint on how to limit string result to only one line? Many thanks in advance!
This is a normal mishap on the 64-bit version of Windows 7, caused by a nasty flaw in that operating system's Wow64 emulator. Not limited to Winforms apps, C++ and WPF apps are affected as well. For .NET apps, this only misbehaves if a debugger is attached. Repro code:
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
throw new Exception("You will not see this");
}
The debugger won't stop when the exception is thrown and you can't close the window anymore. I wrote a more extensive answer about this problem, including recommended workarounds, in this post.
Quick fix in your case: use Debug + Exceptions, tick the Thrown checkbox. The debugger now stops when the exception is thrown, allowing you to diagnose and fix your bug.
Im a beginner, and If statements are my weakness. I have a simple program that displays files names that are located in a certain folder. However, some files might have lines that begin with LIFT. I want to catch those files that have that certain line, and display the file name in a different color (preferably red). Here is what I have so far: Any assistance would be greatly appreciated!! Thanks!
public partial class ShippedOrders : System.Web.UI.Page
{
class Program
{
static void Main()
{
string[] array1 = Directory.GetFiles(#"C:\Kaplan\Replies\");
string[] array2 = Directory.GetFiles(#"C:\Kaplan\Replies\", "*.REP");
Console.WriteLine("---Files:---");
foreach (string name in array1)
{
Console.WriteLine(name);
}
Console.WriteLine("---REP Files: ---");
foreach (string name in array2)
{
Console.WriteLine(name);
}
}
}
}
Directory.GetFiles(directoryPath) will return an array of strings listing the file names (full paths) within that directory. You're going to have to actually open and read each file, using the string array returned. Read each file line by line in a loop and test if any lines begins with "LIFT".
Also the way you set up your code-behind for this webpage is funky. You're declaring a class inside the partial class of the page. Try setting up your code like this:
public partial class ShippedOrders : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
this.goFiles();
}
public void goFiles()
{
string[] array1 = Directory.GetFiles(#"C:\Kaplan\Replies\");
string[] array2 = Directory.GetFiles(#"C:\Kaplan\Replies\", "*.REP");
System.IO.StreamReader file = null;
string line = "";
bool hasLIFT = false;
Response.Write("---Files:---<br/>");
foreach (string name in array1)
{
file = new System.IO.StreamReader(#name);
while((line = file.ReadLine()) != null)
{
if(line.StartsWith("LIFT"))
{
hasLIFT = true;
break;
}
}
if(hasLIFT)
{
Response.Write("<span style=\"color:Red;\">" + name + "</span><br/>";
hasLIFT = false;
}
else
Response.Write(name + "<br/>";
}
//and can do the same for other array
}
}
You can change the console output color by using the Console.ForegroundColor property.
To know if the file contains the text you want, you need to open it and scan the file.
Then do this:
if (fileContainsText) Console.ForegroundColor = ConsoleColor.Red;
else Console.ForegroundColor = ConsoleColor.Gray;
Console.WriteLine(name);
EDIT
I didn't notice you were trying to write to Console inside an ASP.NET server page... in that case you need to tell us what kind of app you are creating... is it a Console application, a WebApplication or a Website... it depends.
The use of Console is not suited for web applications.
EDIT 2
By the way, you may use the Console only in console applications. A console application is a stand-alone windows application, that is different from a web application.
If you ever want to create a console app, in the New Project window, you can find it under Windows category, then you can find a project type called Console Application.
You can do like this inside your foreach loop:
if(name.contains("LIFT"))
{
//make red.
}
it does though have the issue that it only checks if the string (name) contains the string LIFT, and not if the string is in the beginning of the filename. If you want to check if LIFT is in the beggining of the file name you must use some of the Trim methods.
I have a utility programs’s EXE file, when i run this file there is a winform only and there is button when we click on it, it run windows’s notepad. Now I want to hijack this program’s command to run notepad and instead of running notepad I want to run MS Word. I know C# and VB.NET. What I need to do this ?
You can try to add in folder with this program your own program called notepad.exe that should do only one thing: run word.
If you want to do it programatically in C then you should read this page - maybe it helps: Intercepted: Windows Hacking via DLL Redirection
You can use a trick to replace programs with another by making changes to the registry. This will work even if the program you are running uses absolute paths to run notepad. It overrides any instance of the running program with the chosen one no matter where it resides. And you won't have to patch the file. The key you'd be interested in is:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options
Add a key with the name of the program and add a Debugger string with the path to the program you want to replace it with. Of course you need to have permissions to make the necessary modifications. This page explains how you can replace Windows Notepad with another program. You can apply the same process here.
Though you'll probably not want to have this permanent change, so you can write up a program to temporarily add/change the key, run your program then change it back. Here's a complete one I just whipped up to temporarily replace Notepad with Word for a demonstration. Seems to work perfectly fine (though as always, use at your own risk). Just make all the necessary changes to fit your situation.
using System.Diagnostics;
using Microsoft.Win32;
namespace ProgramLauncher
{
class Program
{
// change the following constants as needed
const string PROGRAM_NAME = #"notepad.exe";
const string REPLACEMENT_PATH = #"C:\Program Files (x86)\Microsoft Office\Office12\WINWORD.EXE";
const string RUNNING_PATH = #"C:\Windows\notepad.exe";
// root key
const string KEY = #"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options";
static void Main(string[] args)
{
using (var rootKey = Registry.LocalMachine.OpenSubKey(KEY, RegistryKeyPermissionCheck.ReadWriteSubTree))
{
var oldPath = default(string);
var needsRestoration = false;
try
{
oldPath = BackupKey(rootKey, PROGRAM_NAME, REPLACEMENT_PATH);
needsRestoration = true;
Process.Start(RUNNING_PATH).WaitForExit();
}
finally
{
if (needsRestoration)
RestoreKey(rootKey, PROGRAM_NAME, oldPath);
}
}
}
static string BackupKey(RegistryKey rootKey, string programName, string newPath)
{
Debug.Assert(rootKey != null);
Debug.Assert(!string.IsNullOrEmpty(programName));
Debug.Assert(!string.IsNullOrEmpty(newPath) && System.IO.File.Exists(newPath));
if (newPath.Contains(" "))
newPath = string.Format("\"{0}\"", newPath);
using (var programKey = rootKey.CreateSubKey(programName, RegistryKeyPermissionCheck.ReadWriteSubTree))
{
var oldDebugger = programKey.GetValue("Debugger") as string;
programKey.SetValue("Debugger", newPath, RegistryValueKind.String);
return oldDebugger;
}
}
static void RestoreKey(RegistryKey rootKey, string programName, string oldPath)
{
Debug.Assert(rootKey != null);
Debug.Assert(!string.IsNullOrEmpty(programName));
if (oldPath != null)
{
using (var programKey = rootKey.OpenSubKey(programName, RegistryKeyPermissionCheck.ReadWriteSubTree))
programKey.SetValue("Debugger", oldPath);
}
else
{
rootKey.DeleteSubKey(programName);
}
}
}
}