How to create a text File in solution Explorer? - c#

It's a bit hard to explain but I'll try my best.
I'm not asking how to create a text file or read text file and display. It's more basic than that.
My question is: I've written a paragraph of text file but I don't know how to put it under Solution Explorer, so my program can reference it instead of writing it many times.
Here is one of my coding with a sample string and I have a couple of them using the same text but different tasks. Here I manually(?) wrote the text(string) that I want to save as text file so I can refer to.
string st = "I like apples. I like red apples. I like red apples than green apples";
string result = st.OrderByDescending(s => s.Split(' ').Count()).First();
this.lblMostWordsInSen.Text = result;
Actually, the code above has an error under Split, it says char doesn't contain a definition for Split. How do I fix it?
I've found this coding below "text_file_name.txt" or (#"d:\test.txt") is what I want but file should not be stored in my D drive. It should be stored in my program (Solution Explorer?) I did it in Web application but I don't know how to do in WinForm.
string filename = "Alice-in-Wonderland.txt";
StreamReader sr = new StreamReader("TestFile.txt")
String[] values = File.ReadAllText(#"d:\test.csv").Split(',');
And finally how to call my file is my last question...
Thanks in advance~

Actually, the code above has an error under Split, it says char
doesn't contain a definition for Split. How do I fix it?
string result = st.OrderByDescending(s => s.Split(' ').Count()).First();
it is because string st is a group of characters. in fact it is
st[0],st[1],...,st[st.Length-1]
when you call st.OrderByDescending and supply a lambda expression like s => ..., s does not represent the whole string(st), it just represents elements of st which their type is char and this results to the error we have mentioned above.
You can add a text file to your projects. and if you want to read them you can just read them like this
File.ReadAllText("yourfilename")
but remember to select your file in solution explorer and right click and click properties, then change "Copy to output directory" property to the "Copy always" or "Copy if newer" based on your situation, this will cause that when you build your project, this file will be copied in the directory where your executable file is and you do not need path of it to access it.
you can also go to Build Events tab of your project properties and set actions that will execute when you try to build your project, for example you can set an action to copy "yourfile" to a folder named "text resources" in your build directory, in this approach you can handle more complex situation for example when you have lot of this kind of resources in your project.
you can read this for more information on Build Events

Instead of using the Resources of your program as suggested in the comments already, you could also use a Settings file if you want these Settings to be easily manipulated.
Check this article out: http://msdn.microsoft.com/en-us/library/aa730869(v=vs.80).aspx

Related

Is there any way to automatically add many properties on VS2019?

Don't judge me, but I have an object with over 100 properties, most of them string.
Is there anyway to automatically add them to the code, without extensive typing?
I have them all in a text file with correct casing. I looked for plug ins, but couldn't find any (maybe using wrong keywords?)
I am assuming your file looks like:
Property
SomeOtherProperty
Test
The easiest way would be to use a CSV -> C# Model generator
Steps
Change it to be comma separated, you can do this with C#:
var path = #"C:\Path\To\Your\File.txt";
var text = File.ReadAllText(path);
text = text.Replace(Environment.NewLine, ",");
File.WriteAllText(path, text);
Open the file and copy its contents to your clipboard.
Now open the C# Class from CSV tool.
Paste the contents and voila you have a C# model!
Notepad++ can do it quite easily.
Open your text file with notepad++ and press Ctrl+H
Fill in the fields like below:
search for (.*)
replace with public string \1 {get;set;}
tick "regular expression"
press "Replace all"
And voilĂ :
Note that this should work with any editor that handle regex (as stated by #Klamsi in the comments section)

How to add wildcard on text using BluePrism code stage?

I Have a file name like that "Informe_Pro_Bra-201712110918.xlsx", i can fixe name and date but hours no because it's variable. So i want using code stage of BluePrism (C#) put the last 4 caracters "HHMM" as wilcards, to get others files in this date even with different extension. What do for that?
Help Please
For searching files you can use for that object "Utility - File Management", action: "Get files".
there are two inputs:
Folder
Patterns CSV
Please use Pattern:
"Informe_Pro_Bra-20171211*.xlsx"
That way you can quickly find the file that you're looking for.
Get the all file in the collection and then apply the filter like
"FileName like 'Info_*.xlsx'"
You will be getting another collection with filtered one loop through it.
As we're already having the path append the FileName and generate the dynamic path like
[FTP_Path]&"\"&[Collection.Filename]

Reading particular lines in a text file

I've been having some problems extracting particular lines in a txt file.
I'm using the file to store user names for a login program.
The program will know what line to go to in the text file but I don't know how to actually get the wanted line out and put the resulting string into a variable.
Code I'm using to pull file into a variable is:
string usernameFile = System.IO.File.ReadAllText(#"Usernames.txt");
My real problem is that code two lines below doesn't work in my visual studios community version 2017:
File.ReadLine
I don't know if I need to install something else onto my visual studios but any method to be able to read a particular line of a txt file will be fine.
Use File.ReadAllLines instead. That gives you an array of strings, one for each line.
string[] lines = File.ReadAllLines("Usernames.txt");
string username = lines[2]; // or whatever.
You can use LINQ to avoid reading the entire file:
var line = File.ReadLines("Usernames.txt").Skip(2).First();

R.Net: Sourcing/Parsing a Script.R file Stored as Text File in Visual Studio (C#) Property Resources

I have a R script file, let's call it "Script.R," that I want to source into R from C# (using R.Net). For example, Script.R has several functions in it that I want to call from C#/R.Net.
For deployment purposes, I have added Script.R as a "Resource" in Visual Studio's "Properties." At run time I can get the text of the Script.R file as a C# String by using the "MyProject.Resources.Script" (where it is assumed that the project is called "MyProject" and the Script.R resource is named with the field "Script.")
Now, I know I can use R's "source" function, as called from R.Net, with the file path of the Script.R, e.g.,
rEngine.Evaluate(String.Format("source('{0}')", filePath));
... but, what I am trying to do (and can't seem to figure out) is how to source (or parse?) the Script.R from the MyProject.Resources.Script C# string. That is, I'd like to source my Script.R from the resource C# string rather than from a file.
Any idea how to do this?
Many thanks in advance!
Okay, so after thinking through how to combine C#/R.Net/R, I found a solution. Here's a broken out solution (using many more variables than need be, but hopefully providing more clarity):
String script = MyProject.Resources.Script;
string[] scriptSplit = script.Split(new string[]{"\r\n"}, StringSplitOptions.RemoveEmptyEntries);
SymbolicExpression rscriptSplitSymbolicExpression = rEngine.CreateCharacterVector(scriptSplit);
rEngine.SetSymbol("rscriptSplitSymbolicExpression", rscriptSplitSymbolicExpression);
rEngine.Evaluate("eval(parse(text=rscriptSplitSymbolicExpression))");
Of course, this can be simplified to:
rEngine.SetSymbol("rscriptSplitSymbolicExpression", rEngine.CreateCharacterVector(MyProject.Resources.Script.Split(new string[]{"\r\n"}, StringSplitOptions.RemoveEmptyEntries));
rEngine.Evaluate("eval(parse(text=rscriptSplitSymbolicExpression))");
If you have a different way of doing it, I'd love to see your solution, too! Thanks!

How do I read a tab-delimited file into a List array?

I am firing up Visual C# (2010 Express) for the first time, and I've created a new project for a WindowsFormsApplication. No code has been written yet, but I created a button and placed it on Form1. Then, I double-clicked the button and am taken to the part of the code where you write what happens when the button is push/clicked.
The first thing I would like to do is read data from a LARGE tab-delimited text file (30MB). The text file contains 7 structured columns of data like names, age, favorite color, animal, etc. Nothing tricky or fancy in the text formatting. I'm using the code below:
File.ReadLines(sourceFilePath)
.Select(line => line.Split('\t'))
.ToArray();
But my more basic question is how do I establish and define File and sourceFilePath? With the code above I get "The name 'File' does not exist in the current context.
You need to add the following line to the top of your C# file:
using System.IO;
This will allow the use of the File class, which is in the System.IO namespace.
As for defining sourceFilePath, that's just a variable, which you can declare and set to whatever file path you need, e.g.
string sourceFilePath = #"c:\data\file.csv";
Note the use of # before the string literal; this prevents the backslashes from being treated as the start of escape sequences. You can instead just escape the bakslashes, e.g.
string sourceFilePath = "c:\\data\\file.csv";
If you want to split by tab key then you can try using ReadAllText method, and then a Split method, where you define delimiter (by tab):
string[] delimitedByTab = File.ReadAllText(#"file").Split('\t').ToArray();
And use System.IO; namespace for File class
The File class resides the System.IO namespace. You leverage it in your application with the following:
using System.IO;
As for defining the contents of sourceFilePath, you are going to need either to hard-code the value to a fixed location, which is not always advisable, or devise a mechanism for the user to specify that path, possibly through one of the various CommonDialogs that are available. Some research on the CommonDialogs should help push you a bit further in developing your project.

Categories

Resources