I'm trying to select a set of lines and process each line separately in a text document using c# language. How can i get separate lines to process?
I tried these codes and got struck. Can anyone please help me with this?
EnvDTE.DTE dte = MyPackage.MyPackagePackage.GetGlobalService(typeof(EnvDTE.DTE)) as EnvDTE.DTE;
EnvDTE.TextSelection text = (dte.ActiveDocument.Selection as EnvDTE.TextSelection);
TextSelection interface has got Text property which you can use as string in C#. Further you can split the string to retrieve the lines.
Alternatively TextSelection interface has additional property called TextRanges which has numeric indexers to access each line.
Have a look at this Link form MSDN.
You can use Startpoint and EndPoint for your job.
Also this Link link might be useful to Loop through all the lines from your selection.
If you are reading from a text file this code will help you:
string fileToRead = "D:\\temp.txt"; // Temp.txt is the file to read
if (File.Exists(fileToRead))
{
StreamReader reader = new StreamReader(fileToRead);
do
{
textBox1.Text += reader.ReadLine() + "\r\n"; // Read each line and pass it to the TextBox1
} while (reader.Peek() != -1);
reader.Close(); // Close the file
}
Related
In my Unity3D project I have several text fields. I saved my text in some text files.
When I test my project on the computer everything works fine, and my code reads the text files. But if I upload to my iPad it won't work and the text fields stay empty.
In the image you can see where I have saved my text files.
To read my text files I use the following code:
public Text infoText;
void Update()
{
readTextFile("FileName", "StepNumber")
}
public void readTextFile(string fileName, string stepNumber)
{
StreamReader txt_Reader = new StreamReader("Assets/Resources/Text_Files/" + fileName + ".txt");
while(!txt_Reader.EndOfStream)
{
string txt_String = txt_Reader.ReadLine();
if(txt_String.Contains(stepNumber))
{
string[] separator = { "_" };
string[] strList = txt_String.Split(separator, System.StringSplitOptions.RemoveEmptyEntries);
infoText.text = string.Join("\n", strList.Skip(1));
}
}
}
What do I have to change that my iPad can read from the text files?
EDIT:
My text files looks like this:
Step 1:
* Some Text
* Some Text
Step 2:
* Some Text
* Some Text
* Some Text
Step 3:
* Some Text
Step 4:
* Some Text
So each * should be a new line in my text field. With my old c# code this was no problem, but with
var lines = textFiles.text.Split(new char[] { `*` });
foreach(var line in lines)
{
...
}
i do not know how I can do that, that my text field shows all two lines for step one.
First of all from the Best Practices for the Resources folder
**Don't use it!
Please read the reasons there.
In general for system paths do never use simple string concatenation + "/" +!
Rather use Path.Combine which automatically uses the correct path separators according to the executing platform
Path.Combine(Application.dataPath, "Resources", "Text_Files", fileName + ".txt");
However, you don't/can't simply use a StreamReader to access the Resources folders (See Resources API since it is packed into the build so you have to go through Resources.Load like
// Here you can use / since this is how Unity stores internal paths
// for load you omit the suffix
TextAsset textFile = Resources.Load<TextAsset>("Text_Files/" + filename);
string fileContent = textFile.text;
Or also have a look at Resources.LoadAsync to not block the main thread meanwhile.
BUT
Speaking about blocking the main thread: What you definitely do not want to do is using any of these within Update thus doing heavy FileIO/Loading every frame!
Store the content of that file once as it won't change afterwards anyway!
Depending on your needs you could also simply put your file in any other folder inside the Assets and simply use a TextAsset field directly and drag it into according slot via the Inspector
public TextAsset textFile;
Finally you can then go through the lines one by one using e.g.
var lines = textFile.text.Split(new char[]{'/n'});
foreach(var line in lines)
{
...
}
Note that also that Split is a quite heavy operation since it has to parse every single character in the string and create new substrings so even store these results somewhere in a field of you need them multiple times during runtime!
Typed on smartphone but I hope the idea gets clear
In your case, StreamReader txt_Reader = new StreamReader("Assets/Resources/Text_Files/" + fileName + ".txt"); points to a file on your computer. Assets/Resources/Text_Files/ only exists on your computer.
You need to access a folder that exists on your iPad. It's likely you also didn't save your data to a folder existing on your IPad.
For other devices you could use : Application.persistentDataPath + "/" + fileName
Source: https://docs.unity3d.com/ScriptReference/Application-dataPath.html
I want to add a new line to my txt file.
I tried to write a new line like this:
using (System.IO.StreamWriter file = new System.IO.StreamWriter(#"C:\text.txt",true))
{
file.WriteLine("SOME TEXT");
}
In this way it goes to the last line and writes, but if I want to write, for example on the fourth line without deleting the old data, how I can do this? How I can define that this string must be written in the forth line?
Thank for atention.
You may use this:
var lines = File.ReadLines(#"C:\text.txt").ToList();
lines.Insert(4, "SOME TEXT");
File.WriteAllLines(#"C:\text.txt", lines);
I have a number of text files in a directory which have a set number of columns [6] separated by tabs. I read this into an SSIS package using a 'Flat File Source' block. If a file has more columns than the required number or if data is missing from any of the columns, I want to reject this file.
I have done some testing with various sample files. Whenever I add additional columns, the program accepts these files. It throws an error when there are less columns which is good.
But, is there a way of specifying that the file must have a certain amount of columns and that data must be present in each column?
I don't have much experience with SSIS so I would appreciate any suggestions.
Thanks
I would use a Script Task to do this.
You can use System.IO.StreamReader to open the file and read your header row, and then perform whatever validation you need on the resulting string.
I would also create a Boolean variable in the SSIS package, called something like 'FileIsValid', to which I would write (from the Script Task) True if the conditions are met, and False if they aren't. I would then use this to direct the package flow using precedence constraints.
Something like this:
public void Main()
{
System.IO.StreamReader reader = null;
try
{
Dts.Variables["User::FileIsValid"].Value = false;
reader = new System.IO.StreamReader(Dts.Variables["User::Filepath"].Value.ToString());
string header = reader.ReadLine();
if (header.Trim() == "Column1\tColumn2\tColumn3\tColumn4\tColumn5\tColumn6")
Dts.Variables["User::FileIsValid"].Value = true;
reader.Close();
reader.Dispose();
Dts.TaskResult = (int)ScriptResults.Success;
}
catch
{
if (reader != null)
{
reader.Close();
reader.Dispose();
}
throw;
}
}
With regards to checking there is data in all columns, does this need to be for every row?
You could continue reading the lines with StreamReader and use regular expressions to check for something like this.
Expanding on Chris Mack:
If files do not have headers you can do a count.
char[] delim = new char[] {'\t'};
if(header.Split(delim).Length() == 5)
...
It's simple what I'm trying to do; when I click a button, my app should check if textBox1.Text has a line from a text file.
Note: I don't want to check if textbox has all the text file in it, just to see if it has a LINE from it.
I tried this with no success:
private void acceptBtn_Click(object sender, EventArgs e)
{
StreamReader sr = new StreamReader(usersPath);
string usersTXT = sr.ReadLine();
if (user_txt.Text == usersTXT)
{
loginPanel.Visible = false;
}
}
Hope someone can help me. Thanks in Advance - CCB
string usersTXT = sr.ReadLine();
Reads exactly one line. So you are only checking if you match the first line in the file.
You want File.ReadALlLines (which also disposes the stream correctly, which you aren't):
if (File.ReadAllLines(usersPath).Contains(user_txt.Text))
{
}
That reads all the lines, enumerates them all checking if your line is in the collection. The only downside to this approach is that it always reads the entire file. If you want to only read until you find your input, you'll need to roll the read loop yourself. Do make sure to use the StreamReader in a using block if you take that route.
You can also just use File.ReadLines (thanks #Selman22) to get the lazy enumeration version of this. I would go with this route personally.
Implemenation that shows this at: http://referencesource.microsoft.com/#mscorlib/system/io/file.cs,675b2259e8706c26
if (File.ReadAllLines(path).Any(x => x == line))
{
// line found
}
Replace x == line with a case-insensitive check or Contains if you want.
Try using the Contains() function on the string:
private void acceptBtn_Click(object sender, EventArgs e)
{
StreamReader sr = new StreamReader(usersPath);
string usersTXT = sr.ReadLine();
if (user_txt.Text.Contains(usersTXT))
{
loginPanel.Visible = false;
}
}
I want to know how to read the next line of a text document.
If I click the button, it should open the text document and read the first line.
Then, if I click the "next" button it should read the next line.
How can I do this second button? In C and other languages there are some commands for this..
You need a StreamReader object and then you can invoke the ReadLine method. Don't forget to add the "#" symbol before file path name.
StreamReader sr = new StreamReader(#"C:\\YourPath.txt");
Then on your button clicks you can do:
var nextLine = sr.ReadLine();
The result of each line will be stored in the nextLine variable.
You can use StreamReader.ReadLine
if (myStreamReader.Peek() >= 0)
{
string line = myStreamReader.ReadLine();
}
If you don't want to keep the file open, you can start by reading all lines into memory using File.ReadAllLines
string[] allLines = File.ReadAllLines(path);