mIRC script running a C# program, but getting a FileNotFound error - c#

I'm trying to set up an mIRC bot for my channel, and my current project is playing an audio file on my computer whenever a certain event happens.
I've written a short C# console app that gets the name of the file from the arguments, and plays that file.
This works running it from cmd or using a shortcut, but when I enter the command on my channel, the program comes up, but throws a FileNotFound exception.
I wrote some code using try{} catch{} to see exactly what's happening. In the event that the file fails to play, it will first list the argument that was provided, the extension (I'm going to change this later), and finally the combined string. What it comes up with it this:
args[0]: audiofile
extension: .wav
filename: audiofile.wav
Which is exactly what the file name is, and that plays perfectly from the command line.
Does anybody know what's going on here?
static void Main(string[] args)
{
string extension = ".wav";
string filename = "null";
if (args == null || args.Length == 0)
{
Console.WriteLine("No arguments provided!");
Console.ReadLine();
return;
}
filename = args[0] + extension;
Console.Write("Press enter to play grenade... ");
Console.ReadLine();
try
{
Console.WriteLine("Playing file " + filename);
(new SoundPlayer(filename)).Play();
}
catch
{
Console.WriteLine("Error!");
Console.WriteLine("args[0]: " + args[0]);
Console.WriteLine("extension: " + extension);
Console.WriteLine("filename: " + filename);
}
Console.ReadLine();
}
mIRC script:
on $*:text:!grenade:#: {
/run "c:/users/electrospeed/documents/visual studio 2013/projects/audioplayer/audioplayer/bin/debug/audioplayer.exe" audiofile
}

At the mIRC code, you wrote audiofile at the end, correct me if i'm wrong, but I guess you meant %audiofile like in variable.

I don't think you need the quotation marks in the directory path.

Related

How to setup multiple launch arguments that could be added via batch file launch (C#)

I need to create a console application that can take multiple different launch arguments (which can be added using the batch file). I so far tried this, but it seems like I don't understand it correctly.
Code:
static void Main(string[] args)
{
ProcessStartInfo processStartInfo = new ProcessStartInfo();
processStartInfo.Arguments = LaunchArguments.Operation_AddLocale;
processStartInfo.Arguments = LaunchArguments.Operation_CreateTextFile;
processStartInfo.UseShellExecute = false;
if (processStartInfo.Arguments == LaunchArguments.Operation_CreateTextFile)
{
Console.WriteLine("Creating a text file.");
File.Create("file.txt");
Console.Write("Done!");
}
if (processStartInfo.Arguments == LaunchArguments.Operation_AddLocale)
{
if (Directory.Exists("locale"))
{
try
{
File.Create("locale.txt");
}
catch (Exception ex)
{
Console.WriteLine("An error occured: ");
Console.Write(ex.ToString());
Console.Write(ex.Message.ToString());
Console.ReadLine();
}
}
else
{
Console.WriteLine("Incorrect Input, quitting");
Console.WriteLine("This application only accepts arguments of type '-CreateTextFile; -AddLocale'");
Console.Beep();
Console.ReadLine();
}
}
I made a constant string 'Operation_AddLocale' and 'Operation_CreateTextFile'.
by batch file:
#echo off
start SW_project_generator.exe -AddLocale
This all should do that if I launch the application via this batch file, it will do the operations that are in the 'if (processStartInfo.Arguments == LaunchArguments.Operation_AddLocale)' and if the batch file would add the '-CreateTextFile' argument, it will go to the 'if (processStartInfo.Arguments == LaunchArguments.Operation_CreateTextFile)'.
However, when I launch this app via my batch file, it will always just use the first argument (which is the '-CreateTextFile') and creates a text file and then goes to the else option.
Application's Output:
Creating a text file.
Done!Incorrect Input, quitting
This application only accepts arguments of type '-CreateTextFile; -AddLocale;'
Alright so, my question is, how to make this working, that if I create a batch file give it a argument of type '-AddLocale' it will just go to the 'AddLocale' operations and if I give it something else that is defined in the app, like the 'CreateTextFile', it'll go to it's 'if' statement. And finnaly, if the launch argument will be equal to nothing or wrong one, it'll show the quitting message.
Thanks everyone for help.

Write a new line of code every time the program enters a new string to the file C#

Console.WriteLine("What name would you like to be known as?");
string usernameforscore = Console.ReadLine();
string path = *filepath*;
File.WriteAllText(path, (usernameforscore + " " + classicscore + Environment.NewLine));
So this code is part of a game I'm making for a project, at the end of the game when you fail, I want it to save both a person's chosen username and their score (a variable saved somewhere else). I have got it to save the two to the file, however each time someone enters a new set of data, the file is overridden and only the new data is displayed.
I would like it to write a line with the name and score, then next time the code is run, it will display the new name and score on the next line, creating a high score list.
I'm using visual studio with a console program on C#
Apologies if this is a duplicate, couldn't seem to find a fix myself.
There is a method AppendAllText() rather than WriteAllText(), as below:
File.AppendAllText(#"c:\Path\filename.txt", "the text to append" + Environment.NewLine);
You can use the below method UpdateTextFile to save data to a text file.
public static void UpdateTextFile(string fileName, string content, bool doNotOverwrite = true, bool writeNewLine = true)
{
StreamWriter file = null;
using (file = new System.IO.StreamWriter(#"D:\" + fileName + ".txt", doNotOverwrite))
{
if (writeNewLine)
{
file.WriteLine(content);
}
else
file.Write(content);
file.Close();
}
}
Example of calling the method:
UpdateTextFile("FileName", "file-content", true, false);
Hope it helps.

C# else statement not run when file not found

EDIT:
My problem has been solved thanks to the user Chris Larabell, thank you to all that responded.
The issue that is happening with my code is that when the said file is not present in the Desktop directory, the console will close and will not go to the else statement for what happens when the file is not present. When the file is present however, the console will work completely fine, it is just the else statement.
Here is my code that is being used.
if (inputDrive == "search.system")
{
try
{
string Desktop = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
string DeleteFile = #"delete.txt";
string[] fileList = System.IO.Directory.GetFiles(Desktop, DeleteFile);
foreach (string file in fileList)
{
if (System.IO.File.Exists(file))
{
System.IO.File.Delete(file);
Console.WriteLine("File has been deleted");
Console.ReadLine();
}
else
{
Console.Write("File could not be found");
Console.ReadLine();
}
}
}
catch (System.IO.FileNotFoundException)
{
Console.WriteLine("search has encountered an error");
Console.ReadLine();
}
}
What I am trying to accomplish is to find a file through the Desktop directory with the name of 'delete.txt' and to delete it when the user enters "search.system". the console would then say back to you that the file has been deleted. If the file has not been found, it would say that "the file could not be found" back to you through console. If an error would to occur, it would go to catch and say "search has encountered an error"
I also want to say that I am sorry if this code is messy and/or if this is completely wrong from what I am trying to accomplish. I am new to C#, and new to coding in general.
You would want to put an if statement to check that the fileList length is > 0. If the file length is zero, the file was not found. Otherwise, you can proceed to delete the file.
Also, don’t be discouraged as a new coder. Set a breakpoint at the line where you use the GetFiles() method and step (F11) to the next line. Hover your cursor over the fileList variable and see if the number of items in the array is zero.
System.IO.Directory.GetFiles()
It looks like you are simply looking for a specific file by name and deleting it if it exists. You could simplify your code by doing this:
if (inputDrive == "search.system")
{
try
{
string Desktop = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
string DeleteFile = #"delete.txt";
string filePath = System.IO.Path.Combine(Desktop, DeleteFile);
if (System.IO.File.Exists(filePath))
{
System.IO.File.Delete(filePath);
Console.WriteLine("File has been deleted");
Console.ReadLine();
}
else
{
Console.Write("File could not be found");
Console.ReadLine();
}
}
catch (System.Exception ex)
{
Console.WriteLine($"search has encountered an error: {ex}");
Console.ReadLine();
}
}

Reading a textfile returns zero's in c#

I'm trying to do something basic, read a UTF-8 encoded text file and display it to the console. Everytime I run the script my output is the following:
The file i'm trying to read is here: https://www.gutenberg.org/cache/epub/49724/pg49724.txt
I have no idea why I'm getting this output. I'm sure its something incredibly stupid that I'm overlooking but I've dumbed my code down to the following to try and identify the problem.
static void Main(string[] args)
{
DateTime end;
DateTime start = DateTime.Now;
Console.WriteLine("### Overall Start Time: " + start.ToLongTimeString());
Console.WriteLine();
ReadFile();
end = DateTime.Now;
Console.WriteLine();
Console.WriteLine("### Overall End Time: " + end.ToLongTimeString());
Console.WriteLine("### Overall Run Time: " + (end - start));
Console.WriteLine();
Console.WriteLine("Hit Enter to Exit");
Console.ReadLine();
}
static void ReadFile() {
string fileName = "snow-white.txt";
try
{
foreach (string line in File.ReadLines(fileName, Encoding.UTF8))
{
Console.WriteLine("-- {0}", line);
}
}
catch (Exception Ex)
{
Console.WriteLine(Ex.ToString());
}
}
Any help would be greatly appreciated.
Thanks,
As EZI pointed out, check the contents of the file that gets published to the bin\debug directory and verify that the file was published in the right format.
My problem was that the file's contents was NOT being published correctly. I needed to make sure the file looks the same by going straight to the source.
not my finest moment : )

Ghostscript.NET - no output file when run as Windows service

I'm writing a Windows Service to scan a set of directories for new PDF files and convert them to TIFF with Ghostscript.NET. When I'd compiled and ran the code as a normal program it functioned perfectly, but when I used the same code as a Service the output TIFF never appears. I've set the destination directory to allow writing for Everyone, and the original PDF is being removed as it's supposed to, so it shouldn't be a permissions issue for the "Local System" user. Auditing the directory for access Failures and Successes just shows a list of Successes.
There is a function that reads the color population of the PDF to determine if it's a color document, or B&W scanned as color. That part works, so there isn't an issue accessing and reading the PDF.
I've also tried removing '-q' from the Ghostscript switches and I don't have any errors reported, and "-dDEBUG" outputs so much garbage I don't know what it's saying - but nothing is tagged as an error.
public static void ConvertPDF(string file, GSvalues gsVals)
{
gsProc = new Ghostscript.NET.Processor.GhostscriptProcessor();
System.Collections.Generic.List<string> switches = new System.Collections.Generic.List<string>();
switches.Add("-empty"); // GS.NET ignores the first switch
switches.Add("-r" + gsVals.Resolution); // dpi
switches.Add("-dDownScaleFactor=" + gsVals.ScaleFactor); // Scale the image back down
switches.Add("-sCompression=lzw"); // Compression
switches.Add("-dNumRenderingThreads=" + Environment.ProcessorCount);
switches.Add("-c \"30000000 setvmthreshold\"");
switches.Add("-dNOGC");
string device;
if (_checkPdf(file, gsVals.InkColorLevels, gsVals))
{
gsVals.WriteLog("Color PDF");
device = "-sDEVICE=tiffscaled24"; // 24bit Color TIFF
}
else
{
gsVals.WriteLog("Grayscale PDF");
device = "-sDEVICE=tiffgray"; // grayscale TIFF
}
switches.Add(device);
// Strip the filename out of the full path to the file
string filename = System.IO.Path.GetFileNameWithoutExtension(file);
// Set the output file tag
string oFileName = _setFileName(oPath + "\\" + filename.Trim(), GSvalues.Extension);
string oFileTag = "-sOutputFile=" + oFileName;
switches.Add(oFileTag);
switches.Add(file);
// Process the PDF file
try
{
string s = string.Empty;
foreach (string sw in switches) s += sw + ' ';
gsVals.DebugLog("Switches:\n\t" + s);
gsProc.StartProcessing(switches.ToArray(), new GsStdio());
while (gsProc.IsRunning) System.Threading.Thread.Sleep(1000);
}
catch (Exception e)
{
gsVals.WriteLog("Exception caught: " + e.Message);
Console.Read();
}
gsVals.DebugLog("Archiving PDF");
try
{
System.IO.File.Move(file, _setFileName(gsVals.ArchiveDir + "\\" + filename, ".pdf"));
}
catch (Exception e)
{
gsVals.WriteLog("Error moving PDF: " + e.Message);
}
}
private static string _setFileName(string path, string tifExt)
{
if (System.IO.File.Exists(path + tifExt)) return _setFileName(path, 1, tifExt);
else return path + tifExt;
}
private static string _setFileName(string path, int ctr, string tifExt)
{
// Test the proposed altered filename. It it exists, move to the next iteration
if(System.IO.File.Exists(path + '(' + ctr.ToString() + ')' + tifExt)) return _setFileName(path, ++ctr, tifExt);
else return path + '(' + ctr.ToString() + ')' + tifExt;
}
This is a sample output of the generated switches (pulled from the output log):
Switches: -empty -r220 -dDownScaleFactor=1 -sCompression=lzw -dNumRenderingThreads=4 -c "30000000 setvmthreshold" -dNOGC -sDEVICE=tiffscaled24 -sOutputFile=\\[servername]\amb_ops_scanning$\Test.tiff \\[servername]\amb_ops_scanning$\Test.pdf
Settings are read in an XML file and stored in a class, GSVals. The class also handles writing to the System log for output, or to a text file in the normal Program version. GSSTDIO is a class for handling GS input and output, which just redirects all the output to the same logs as GSVals. The only code changes between the Program version and the Service version is the Service handling code, and the output is changed from a text file to the system logs. Nothing about the Ghostscript processing was changed.
This is being compiled as x86 for portability, but is being run on x64. GS 9.15 is installed, both x86 and x64 versions. GS.NET is version 4.0.30319 installed via NuGet into VS 2012. ILMerge 2.13.0307 is being used to package the GS.NET dll into the exe, also for portability. None of these things changed between the normal EXE and the Windows Service versions, and as I said the normal EXE works without any issues.
I got it working by using CreateProcessAsUser() from advapi32.dll, using code from this article.
I also had to restructure the order of the switches:
switches.Add("-c 30000000 setvmthreshold -f\"" + file + "\"")
The original source I'd used for speeding up the conversion left out the '-f' part, and the fact that the -f was the tag marking the file. I don't know why this worked in GS.NET, but with normal gswin32c.exe I got an error saying that it was an invalid file, until I set the switch this way.
Oddly, the processes this method creates are still Session 0, but it actually works. I'll keep tinkering, but for now it's working.

Categories

Resources