This is my code:
string path = #"c:\temp\mytext.txt";
string[] lines = System.IO.File.ReadAllLines(path);
foreach (var line in lines)
{
var firstValue = line.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries)[0];
Console.WriteLine(firstValue);
System.IO.File.WriteAllLines(#"C:\temp\WriteLines.txt", firstValue);
}
I want to export my first value to a text file. How i can export it?
I get this error:
Cannot convert from 'string' to 'System.Collections.Generic.IEnumerable'
at this line
System.IO.File.WriteAllLines(#"C:\temp\WriteLines.txt", firstValue);
File.WriteAllLines takes a sequence of strings - you've only got a single string.
If you only want your file to contain that single string, just use File.WriteAllText:
File.WriteAllText(#"C:\temp\WriteLines.txt", firstValue);
However, given that you've got this in a loop it's going to keep replacing the contents of the file with the first part of each line of the input file.
If you're trying to get the first part of each line of your input file into your output file, you'd be better off with:
var query = File.ReadLines(inputFile)
.Select(line => line.Split(new string[] { " " },
StringSplitOptions.RemoveEmptyEntries)[0]);
File.WriteAllLines(outputFile, query);
Note that with a using directive of
using System.IO;
you don't need to fully-qualify everything, so your code will be much clearer.
Related
My goal is to match the users input into a field with data in a text file.
1000|I-002096.02.02|EL|MISCMI
1000|I-002097.02.02|EL|ESYEED
1000|I-002098.02.02|EL|MISCCA
1000|I-002099.02.02|EL|MISCCA
1000|I-002100.02.02|EL|MISCCA
1000|I-002101.02.02|EL|USQUIC00
1000|I-002102.02.02|EL|MISCMI
The portion after the first "|" delimiter is what I need to check against the users input. (users input is stored in TxtWBS.Text in the code below)
This is what I have tried but this only works when each line has nothing to delimit.
string[] wbslist = File.ReadAllLines(filePath);
bool wbsExists = Array.Exists(wbslist, element => element == TxtWBS.Text);
if (wbsExists)
/*leave empty*/;
else
errMessage += "This WBS does not exist" + Environment.NewLine;
I expect to be able to check if the users input exists in the text file.
This could be done with a single line in Linq.
Change your test to:
bool wbsExists = wbslist.Any(x => x.Contains(TxtWBS.Text));
And if you are not sure about the case of the input you can have
bool wbsExists = wbslist.Any(x => -1 != x.IndexOf(TxtWBS.Text, StringComparison.CurrentCultureIgnoreCase));
More, if you want to check an exact match against the second item in the line then
bool wbsExists = wbslist.Select(x => x.Split('|')[1]).Any(k => k == TxtWBS.Text);
Consider also to change the loading of your text data to
var wbslist = File.ReadLines(filePath);
File.ReadLines doesn't read all the lines in memory immediately but returns an IEnumerable<String> that is more suited in Linq expressions
You can use the following code. Read file and iterate line by line, splitting each line into array of strings by token '|'.
string[] wbslist = File.ReadAllLines(filePath);
foreach(string line in wbslist)
{
string [] splittedLine = line.Split('|');
// I assume you need the second element in the delimited line
if(string.Equals(splittedLine[1], TxtWBS.Text, StringComparison.OrdinalIgnoreCase))
Console.WriteLine("Website found");
}
Well, if you're absolutely sure about the format of the file then you can split each line on the delimiter and check the user input against the second element in the resulting array.
bool wbsExists = Array.Exists(wbslist, element => element.Split('|')[1] == TxtWBS.Text);
I am trying to write the values of my array to a text file, but my output isn't cooperating.
my code
using (StreamWriter outputFile = new StreamWriter(#"C:\Users\fakeuser\Desktop\C#\New Text Document.txt"))
{
string[] values = { "Test", "People", "Owls", "Bully"};
foreach (string line in values)
outputFile.WriteLine(values);
this is the output I get
What am I missing here?
The problem is you're writing the array instead of the line you're iterating over. Try this instead:
outputFile.WriteLine(line);
Alternatively, you could replace the whole loop with this:
File.WriteAllLines("that long path", values);
You have a typo in your code. Try this:
outputFile.WriteLine(line);
I have a (perhaps) simple question about reading a text file in Unity (C#) containing a matrix of floats, and converting it to a matrix (or multiple arrays) of floats. Before even getting there, I seem unable to succesfully convert the 'string'-typed text to an array using the .Split method.
To summarize, I need the weights of an artificial neural network, which are trained in MATLAB, in my Unity script to use for calculating outputs and performing certain actions.
I will show you carefully what I tried; First of all, the "WeightsIH.txt" file I intend to read looks like this:
-0.493654767886117 1.96685485682002
-0.493654767886117 1.96685485682002
-1.12167737625244 -0.835107290621868
-0.168882176970878 -0.0508678270221517
0.00848314746590752 0.645890421329432
-0.445148017062813 -0.647593931130814
0.0719861441229913 0.00251854104000363
-0.0809087627607675 -0.00253116474618752
0.0677112130287254 0.00229085080614581
0.0754386783608645 0.00239167974789985
0.0809669296303145 0.00253343860819182
-3.54887781611766 -0.884835613897628
-0.459886351851150 -0.848445431434901
-0.0670274486060166 -1.39397672397051
-3.82077442331056 -2.40290337409384
0.0783082838340459 0.00245132734091342
-0.239255503684809 -0.0118048053697862
-0.0798562101865881 -0.00249224979249840
-0.0639184016149756 -0.00224822783089479
-0.778070988555323 -0.872732391008980
0.0297507291420014 -1.74952458318966
0.0963966379119354 0.00416637970011285
0.875794416782941 0.513267873404847
0.0788049456605797 0.00246400296768071
-0.301882135742981 1.29009004735214
-0.427112778202037 -0.602081710823938
-0.0287160010856207 0.876736618413824
0.174484840994587 -0.914135602108887
-1.13771093704277 -1.80803211709460
-0.842897124110693 -0.491320433352398
-0.883862027266628 0.577867664170583
-0.00732465337711950 -0.0608133682721268
0.0808154577205481 0.00252756604265255
-0.623653482256716 0.802021714172196
0.354715179032082 -1.40951283673210
0.107130434979695 0.00718795362864938
-3.25429700675793 1.15179026184665
0.00323132998826740 0.725967105940923
-0.445271160376852 -0.634848835782688
0.0353267566953751 -0.761005808087746
0.343818927585420 0.181552084533698
1.52333372694938 -1.95500299702055
1.28692979700544 2.03963829780562
0.665570336193150 -0.410729910590931
-0.0861536175683719 -0.00286332759826070
0.126619076047933 0.0171533754647685
-0.0822566525595005 -0.00259193055392493
-1.28712374245194 1.12380947288866
-1.29253445353219 -2.05175940341935
0.416493102590467 -0.617909454448863
0.0969179981825367 0.182721981022912
-0.0808788394332979 -0.00252999992128388
0.925818615324062 -1.91710736361040
-0.438361270919922 0.0119396635243124
1.05250770533487 -0.965588245752274
-0.0480257526132498 -0.00154845733604858
-0.0586872685404968 -0.00184430469780941
-0.471992797137374 -0.672492593551730
0.439729645530884 1.55878656878788
1.68156076364744 1.32277838623733
-0.455916176089339 -0.632974493608950
-2.76038741468600 1.87628535124240
0.993963121269136 0.412382925821147
0.0813294944564905 0.00254834378164385
1.05785147371486 -0.713165079912121
0.542621317508334 0.263699015691544
0.0859471661820603 0.00284559667679037
0.0752254002940845 0.00264837949098051
-0.0821494531270125 -0.00258646752960803
-0.135286303232541 -0.0230503985166856
-1.04824146276167 0.379479302836832
-1.00411135626130 0.643815076295448
-1.06427192746705 -1.71485567599474
0.0306923117644997 -0.326399702175058
-0.269230352435044 1.15492815472443
-1.09071040094221 0.974587786723127
-0.0811137162377503 -0.00253932111442298
0.843300471645878 -0.443547135621555
2.62543922875650 -1.43287453338882
-0.0879222032042109 -0.00305697486042674
1.08943207983567 -0.751402936369758
-0.0807147111768526 -0.00252376120454932
0.0920673615786699 0.00345537914425264
-3.32572250550751 2.23334579177979
0.567347532732561 -0.849919751538726
-0.981291377531284 -1.65375737600341
0.717607651399507 -0.501535458162733
Now my C# Unity code looks like this:
using UnityEngine;
using System.Collections;
using System;
using System.IO;
public class WeightsMDF : MonoBehaviour
{
private string text;
void Start ()
{
FileInfo theSourceFile = new FileInfo
("C:/Users/Ajdin/Downloads/UnitySpace/minorProject/Nerd/Nerds/Assets/Scenes/WeightsIH.txt");
StreamReader reader = theSourceFile.OpenText();
do
{
text = reader.ReadLine();
string[] floats = text.Split(" "[0]);
//Console.WriteLine(text);
print (text);
//print(floats[0]);
} while (text != null);
}
}
Now this code gives me the entire textfile in the console, but with a nullreferenceexeption at last:
NullReferenceException: Object reference not set to an instance of an object
WeightsMDF.Start () (at Assets/Scripts/Nerds/WeightsMDF.cs:19).
This exception refers to line 19:
string[] floats = text.Split(" "[0]);
Now if I comment this line, I get the same output except the last console output line says
Null
And If I change line 19 to:
string[] floats = text.Split(" ");//[0]);
I get the following compiling error:
Assets/Scripts/Nerds/WeightsMDF.cs(19,36): error CS1502: The best overloaded method match for `string.Split(params char[])' has some invalid arguments
Assets/Scripts/Nerds/WeightsMDF.cs(19,36): error CS1503: Argument `#1' cannot convert `string' expression to type `char[]'
Does anyone know what I'm doing wrongly?
Thanks in advance!
Try to check text before use split. ReadLine returns null at the end of file, so you need check it before split.
text = reader.ReadLine();
if (text == null)
break;
string[] floats = text.Split(" "[0]);
Also, you can use Peek. It returns next symbol and doesn't use it and -1 if no symbols left.
using (StreamReader sr = new StreamReader(path))
{
while (sr.Peek() >= 0)
{
text = sr.ReadLine();
var splits = text.Split (new string[] {" "}, StringSplitOptions.RemoveEmptyEntries);
}
}
To split string by whitespace you can use
string[] splits = text.Split(null);
string[] splits = text.Split(new char[0]);
Instad of doing a do while loop, use a while loop with the condition: (!reader.EndOfStream).
For the split problem you need to send as parameter a char and not a string. with ' ' instead of " " like:
string[] floats = text.split(' ');
i have a 1000 text file and i want read single to single and Each file has a 4700000 record,for example one of line in file is:
43266200 6819 43295200 1393/05/23 14:28:45 113 1
and i want save into sql server for example:
field1:43266200
field2:6819
how can i do this?
var seperators = " ".ToCharArray();
foreach(var line in File.ReadLines(path))
{
var fields = line.Split(seperators, StringSplitOptions.RemoveEmptyEntries);
//now you have fields[0] and fields[1], save them in your database
}
This may help you
var message ="43266200 6819 43295200 1393/05/23 14:28:45 113 1";
//Split your data into pieces
var messages=message.Split(' ').Where( o => !string.IsNullOrEmpty(o));
var i=0;
foreach(var item in messages)
{
// do whatever you wanna to do with pieces
Console.Write( "field {0}:{1}",++i,item);
}
If you're reading the text from a file, and you can reasonably assume that the space character will be your only delimiter, you should use the String.Split() method to tokenize each line:
// instantiate FileInfo of your file as yourFile
foreach (string line in yourFile.ReadLines())
{
string[] lineTokens = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
}
String.Split() allows you to separate any string into a string[] of substrings based on the char delimiters you provide in the first argument. The second argument in the code above is one of the values in the StringSplitOptions enumeration, which has values of either None (provide all strings) or RemoveEmptyEntries (do not return any substrings that consist solely of delimiter characters).
Then, from there, you can iterate through lineTokens and assemble an object from each token, or you can assemble an SQL query where any given index corresponds to a column in the row you intend to add.
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int y;
FileInfo fi;
string[] newDest_files;
string[] lines = global::EachFileDirectory.MyResource.video_formats.Split (new Char[] {'\r','\n'});
foreach (string line in lines)
{
newDest_files = Directory.GetFiles(Environment.CurrentDirectory, line); //strFilter );
for (y = 0; y < newDest_files.Length; y++)
{
fi = new FileInfo(newDest_files[y]);
string newFolder = Path.Combine(fi.DirectoryName, fi.Name + "_Directory");
if (!Directory.Exists(newFolder))
Directory.CreateDirectory(newFolder);
Console.WriteLine("processed: " + line.Length + " files");
File.Move(fi.FullName, Path.Combine(newFolder, fi.Name));
}
if (newDest_files.Length == 0)
{
Console.WriteLine(line + "No files found in the current directory of format: ");
}
}
Console.WriteLine("\n Done! Press any key to exit...");
Console.ReadKey();
}
}
}
The problem is when i have added the line: string[] lines = global::EachFileDirectory.MyResource.video_formats.Split(new Char[] {'\r','\n'});
Since then i see in the console window all the lines double for example:
*.264 No files found in the current directory of format:
No files found in the current directory of format:
*.mov No files found in the current directory of format:
No files found in the current directory of format:
What i need to see in the console window is:
*.264 No files found in the current directory of format:
*.mov No files found in the current directory of format:
And so on but since i have the line: string[] lines = global::EachFileDirectory.MyResource.video_formats.Split(new Char[] {'\r','\n'});
And also the line in the end of the code: Console.WriteLine(line + "No files found in the current directory of format: ");
I see No files found in the current directory of format: also in between each line.
How can i fix it ?
On the reference of the project i added a text file wich contain many video formats extentions in this way:
*.264
*.mov
*.avi
and so on.....
The problem is that the text: No files found in the current directory of format:
Appears near each format and also between two formats and i want ti to be in the console window only near each format !
Thanks a lot.
You're splitting on \r and \n - which means you're turning input of something like
"foo\r\nbar"
into:
{ "foo", "", "bar" }
... so you're then trying to find all the files with an empty pattern.
There are various options:
Create a StringReader and call ReadLine multiple times instead of using Split
Replace \r with the empty string before splitting
Split on just \n and then trim each entry
Specify StringSplitOptions.RemoveEmptyEntries after splitting
Add StringSplitOptions.RemoveEmptyEntries to Split method:
string[] lines = global::EachFileDirectory.MyResource.video_formats.Split(new Char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);