how to place text inside quotes - c#

I'm trying to add your computer name to the name of the plugin text. Here is a example:
I have a path which detects file which is here:
string pypath = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData)
+ "\\elfen_encore\\extra_maya\\mayaplugins\\CoDMayaTools.py";
From there I use this code to access a string in there
public void changepy()
{
if (File.Exists(pypath))
{
{
string quotes = "\"\"";
string name = System.Environment.MachineName;
string text = File.ReadAllText(pypath);
text = text.Replace("\"Call of Duty Tools\"", quotes + name);
File.WriteAllText(pypath, text + name);
}
MessageBox.Show("Changed ");
}
else
{
}
Then this is the file it should change to computer name :
OBJECT_NAMES = {'menu' : ["CoDMayaToolsMenu",
"Call of Duty Tools", None, None, None],
"CoDMayaToolsMenu" is the issue; I want to replace that with the users computer name but as you can see its in quotes and I am having huge issues on trying to get the text in the quotes. How can I solve it?

Is this what you are trying to do?
text = text.Replace("\"Call of Duty Tools\"", "\"" + name + "\"");
If not, please specify a little bit more your question or your desired output.

If you're leaving the quotes anyway, why not this approach? ... It's a bit unclear if this is what you're trying to accomplish?
public void changepy()
{
if (File.Exists(pypath))
{
string machineName = System.Environment.MachineName;
string content = File.ReadAllText(pypath);
content = content.Replace("Call of Duty Tools", machineName);
File.WriteAllText(pypath, content);
MessageBox.Show("Changed");
}
else
{
}
}

Related

c# RawPrintHelper. How can i send a BOLD command

I have this piece of code to send some text lines to a dot matrix ticket printer.
public static void PrintInvoice(string PrinterName, Ticket ticket)
{
string s = string.Empty;
string COMMAND = Convert.ToString((char)29) + "V" + Convert.ToString((char)66) + Convert.ToString((char)0);
foreach (string k in ticket.Data)
{
s = s + k + Environment.NewLine;
}
s = s + COMMAND;
RawPrinterHelper.SendStringToPrinter(PrinterName, s);
}
It works fine but i need to set BOLD or SIZED font in one of the lines.
I've searched everywhere but i couldnt find the way for sending a BOLD o SIZE command to RawPrinterHelper.
I would appreciate any help.
Regards,
I am not sure if RawPrintHelper is your only choice; I was able to locate this which uses PrintDocument instead and allows Bold functionality.

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.

Make syntax shorter when using if & else with statements

I'm currently working on a dll library project.
if (!Directory.Exists(MenGinPath))
{
Directory.CreateDirectory(MenGinPath + #"TimedMessages");
File.WriteAllLines(MenGinPath + #"TimedMessages\timedmessages.txt", new string[] { "Seperate each message with a new line" });
}
else if (!File.Exists(MenGinPath + #"TimedMessages\timedmessages.txt"))
{
Directory.CreateDirectory(MenGinPath + #"TimedMessages");
File.WriteAllLines(MenGinPath + #"TimedMessages\timedmessages.txt", new string[] { "Seperate each message with a new line" });
}
As you can see if the statement Directory.Exists is false a specific directory (MenGinPath) will be created. However, if the same path, with another file in addition is false, the second functions will be called.
My question is the following: is there any way to make this shorter?
Because as you can see I'm calling 2 times the same functions:
Directory.CreateDirectory(MenGinPath + #TimedMessages\timedmessages.txt
and
File.WriteAllLines(MenGinPath + #"\TimedMessages\timedmessages.txt"))
Any help would be welcome!!
You don't need to check if directory exists because Directory.CreateDirectory automatically creates the directory if it does not exists and does nothing if the directory already exists.
Also, do not include the filename when creating the directory. Yes, it wont error but just for clarity sake.
Another one is to use Path.Combine instead of hardcoding the path. This will improve readability of your code.
So, here's what I can come up with:
string dir = Path.Combine(MenGinPath, #"Groups\TimesMessages");
string file = Path.Combine(dir, "timedmessages.txt");
// this automatically creates all directories in specified path
// unless it already exists
Directory.CreateDirectory(dir);
//of course, you still need to check if the file exists
if (!File.Exists(file) {
File.WriteAllLines(filePath, new string[] { "Seperate each message with a new line" });
}
/* or if file exists, do your stuff (optional)
* else {
* //do something else? maybe edit the file?
* }
*/
You can make your code shorter given the fact that CreateDirectory does nothing when the directory exists. Moreover do not pullute your code with all that string concatenations to create the path and the file names.
Just do it one time before entering the logic using the appropriate method to create filenames and pathnames (Path.Combine).
string messagePath = Path.Combine(MenGinPath, "TimedMessages");
string fileName = Path.Combine(messagePath, "timedmessages.txt");
// call the create even if it exists. The CreateDirectory checks the fact
// by itself and thus, if you add your own check, you are checking two times.
Directory.CreateDirectory(messagePath);
if (!File.Exists(fileName)
File.WriteAllLines(fileName, new string[] { "Seperate each message with a new line" });
Would something like this work?
string strAppended = string.Empty;
if (!Directory.Exists(MenGinPath))
{
strAppended = MenGinPath + #"Groups\timedmessages.txt";
}
else if (!File.Exists(MenGinPath + #"TimedMessages\timedmessages.txt"))
{
strAppended = MenGinPath + #"TimedMessages\TimedMessages.txt";
}
else
{
return;
}
Directory.CreateDirectory(strAppended);
File.WriteAllLines(strAppended, new string[] { "Seperate each message with a new line" });
I have found that it is a great idea to reuse blocks of code like this instead of hiding them in if statements because it makes code maintenance and debugging easier and less prone to missed bugs.
It seems the only difference between the 2 cases is the path. So just get only this path in your if-else
const string GroupsPath = #"Groups\timedmessages.txt";
const string TimedMessagesTxt = #"TimedMessages\TimedMessages.txt";
string addPath = null;
if (!Directory.Exists(MenGinPath)) {
addPath = GroupsPath;
} else if (!File.Exists(Path.Combine(MenGinPath, TimedMessagesTxt))) {
addPath = TimedMessagesTxt;
}
If (addPath != null) {
Directory.CreateDirectory(Path.Combine(MenGinPath, addPath));
File.WriteAllLines(Path.Combine(MenGinPath, TimedMessagesTxt),
new string[] { "Seperate each message with a new line" });
}
Note: Using Path.Combine instead of string concatenation has the advantage that missig or extra \ are added or removed automatically.

Code to reformat file

Need help formatting a seperated .txt file in C#. I have a text file that contains a directory listing and looks like as follows when I open up in notepad or ultra-edit. First column is date and time, next column is the size of file in bytes, third column is the username and fourth column is the name of the file. Each column is separated by one or more spaces, and the filename column at the end can contain spaces in the filename. They consist of more directories and the total amount of lines in the file is about 200,000.
Directory of V:\word
01/10/2013 12:30 PM 23,000 BUILTIN/ADMINISTRATOR FILE NAME.XLS
10/25/2013 10:39 AM 1,332,432 AMERICAS/DOEJ FILENAME2.CSV
11/31/2000 09:54 PM 21,999,999 AMERICAS/DOEF F_I_L_E_N_A_M_E_4.PDF
Directory of V:\word\administrators
01/10/2013 12:30 PM 23,000 BUILTIN/ADMINISTRATOR FILENAME.XLS
10/25/2013 10:39 AM 1,332,432 AMERICAS/DOEJ FILENAME2.CSV
11/31/2000 09:54 PM 21,999,999 AMERICAS/DOEF F_I_L_E_N_A_M_E_4.PDF
My goal is to try and add the path of the directory (ex. V:\Word or other directories) in a fixed format at the end of the filename. So Once you see the "Directory V:\word" then you know every line after and up until a new Directory, should show that path at the end of the filename. This would be considered the fifth column.
Here is some code, but I still need to help. I am able to get V:\word at the end of the file, but how do I read the new directory and append that to the end of the lines for all subsequent lines?
private void button1_Click(object sender, EventArgs e)
{
var sbText = new StringBuilder(10000);
string currLine = " Directory of V:\\word ";
try
{
using (StreamReader Reader = new StreamReader(#"C:\V.txt"))
{
while (!Reader.EndOfStream)
{
if (currLine != " Directory of V:\\word ")
{
MessageBox.Show("No Directory");
}
else
{
sbText.AppendLine(Reader.ReadLine() + "V:\\word");
}
}
// When all of the data has been loaded, write it to the text box in one fell swoop
richTextBox1.Text = sbText.ToString();
using (StreamWriter Writer = new StreamWriter(#"C:\NEWFILE.txt"))
{
Writer.WriteLine(sbText);
}
}
}
catch (Exception ex)
{
MessageBox.Show("An error has occured. " + ex.Message);
}
Here's a fairly straight-forward approach--which defines a simple class that represents your data, and parses each line into a class instance. It's efficient, and the results can easily be written to a new file, queried, or displayed:
void Main()
{
var lines = ReadFile();
lines.ToList().ForEach (Console.WriteLine);
}
IEnumerable<Line> ReadFile()
{
using (var reader = new StreamReader(File.OpenRead(#"file.txt")))
{
const string directoryPrefix = " Directory of ";
Regex splittingRegex = new Regex(#"\s+", RegexOptions.Compiled);
string directory = null;
string line;
while ((line = reader.ReadLine()) != null)
{
line = line.TrimEnd();
if (line.StartsWith(directoryPrefix))
{
directory = line.Substring(directoryPrefix.Length);
continue;
}
// The "6" parameter means the regex will split the string into 6 parts at most--leaving the last column (filename) unsplit
var lineParts = splittingRegex.Split(line, 6);
yield return new Line{ Date = lineParts[0], Time = lineParts[1], Period = lineParts[2], Bytes = lineParts[3], User = lineParts[4], Filename = Path.Combine(directory, lineParts[5]) };
}
}
}
// Define other methods and classes here
class Line
{
public string Date{get;set;}
public string Time {get;set;}
public string Period {get;set;}
public string Bytes {get;set;}
public string User {get;set;}
public string Filename {get;set;}
}
Note: This is derived from a couple helper methods for parsing simple text files. One of my earlier revisions include the helper methods, which might be of use to you (but aren't quite suited for this due to the need to remember the directory value).
You're incrementing wCurrLine but never resetting it. I think you want to reset it after each directory?
You're not incrementing totalLines, but then displaying it in label2. I think you should be incrementing it.
How do you check if the input line of text is a directory entry? If your text is consistent as presented, you could check the first letter of each row as it's read in and check if it is the letter 'D'.
You need to AppendLine not Append to put the carriage returns back in

Trailing slash(/) is added in arguments

I'm registering a custom protocol handler on my computer, which calls this application:
string prefix = "runapp://";
// The name of this app for user messages
string title = "RunApp URL Protocol Handler";
// Verify the command line arguments
if (args.Length == 0 || !args[0].StartsWith(prefix))
{
MessageBox.Show("Syntax:\nrunapp://<key>", title); return;
}
string key = args[0].Remove(0, "runapp://".Length);
key.TrimEnd('/');
string application = "";
string parameters = "";
string applicationDirectory = "";
if (key.Contains("~"))
{
application = key.Split('~')[0];
parameters = key.Split('~')[1];
}
else
{
application = key;
}
applicationDirectory = Directory.GetParent(application).FullName;
ProcessStartInfo psInfo = new ProcessStartInfo();
psInfo.Arguments = parameters;
psInfo.FileName = application;
MessageBox.Show(key + Environment.NewLine + Environment.NewLine + application + " " + parameters);
// Start the application
Process.Start(psInfo);
What it does is that it retrieves the runapp:// request, split it into two parts: application and the parameters passed, according to the location of the '~' character. (This is probably not a good idea if I ever pass PROGRA~1 or something, but considering I'm the only one using this, it's not a problem), then runs it.
However, a trailing '/' is always added to the string: if I pass
runapp://E:\Emulation\GameBoy\visualboyadvance.exe~E:\Emulation\GameBoy\zelda4.gbc, it will be interpreted as
runapp://E:\Emulation\GameBoy\visualboyadvance.exe E:\Emulation\GameBoy\zelda4.gbc/.
Why would it do this ? And why can't I get rid of this trailing slash ? I tried TrimEnd('/'), Remove(key.IndexOf('/'), 1), Replace("/", ""), yet the slash stays. What is happening ?
You need to assign the result of the TrimEnd:
key = key.TrimEnd('/');
Strings in C# are immutable; therefore string methods which alter the string return a new string with the alterations, rather than changing the original string.

Categories

Resources