How write a .txt file in c# using StreamReader in Metro App? - c#

I'm having trouble creating a StreamReader object in Windows 8 metro application. I'm trying to make it read the text file in my local directory but it keep showing me this error. Anyone has any solutions for this or any other alternative solutions?
I'm using MS Visual Studio Ultimate 2012, metro application.
Code:
int level = 1;
var fileName = string.Format(#"Mazes\level{0}.txt", level);
using (var sr = new StreamReader(fileName))
{
var l = 0;
while (!sr.EndOfStream)
{
string line = sr.ReadLine();
for (var c = 0; c < line.Length; c++)
{
mazeValues[c, l] = line[c];
if (mazeValues[c, l] == '1')
{
var glass = new Glass();
glass.SetValue(Grid.ColumnProperty, c);
glass.SetValue(Grid.RowProperty, l);
grdMaze.Children.Add(glass);
mazeGlasses[c, l] = glass;
}
}
l++;
}
}
Error showing:
The best overloaded method for
'System.IO.StreamReader.StreamReader(System.IO.Stream)' has some
invalid arguements.

Windows.Storage.StorageFile.GetFileFromApplicationUriAsync and Windows.Storage.FileIO.ReadLinesAsync can be used for this.
using System;
using Windows.Storage;
async void test2()
{
var fileName = string.Format(#"ms-appx:///Mazes/level{0}.txt", level);
try
{
var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri( "ms-appx:///assets/textfile1.txt"));
var lines = await FileIO.ReadLinesAsync(file);
foreach (var line in lines)
{
// code to process each line here
}
}
catch (Exception e)
{
// handle exceptions
}

WebClient client = new WebClient();
System.IO.Stream stream = client.OpenRead(path_of_text _file);
System.IO.StreamReader str = new StreamReader(stream);
string Text = str.ReadLine();
while (!Text.EndOfStream)
{
string line = Text.ReadLine();
for (var c = 0; c < line.Length; c++)
{
mazeValues[c, l] = line[c];
if (mazeValues[c, l] == '1')
{
var glass = new Glass();
glass.SetValue(Grid.ColumnProperty, c);
glass.SetValue(Grid.RowProperty, l);
grdMaze.Children.Add(glass);
mazeGlasses[c, l] = glass;
}
}
l++;
}

Related

How do i change a specific line in a textfile

Im trying to read from a textfile into an array, change one element and then read array back into the file but not appending the original text. But it says the file is being used by another process. Any help is appreciated.
using (StreamReader readName = new StreamReader("fileA"))
{
using (StreamReader readColour = new StreamReader("fileB"))
{
var lineCount = File.ReadLines("fileB").Count();
string[] linesA = new string[lineCount];
string[] linesB = new string[lineCount];
for (int a = 0; a < linesA.Length; a++)
{
if (linesA[a] == UserVariables.userNameC)
{
linesB[a] = UserVariables.colourC.ToString();
}
}
}
}
try
{
using (StreamWriter colourWrite = new StreamWriter("fileB"))
{
for (int a = 0; a < linesB.Length; a++)
colourWrite.WriteLine(linesB[a], false);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Error");
}
}
You are trying to read fileB twice,
using (StreamReader readColour = new StreamReader("fileB")) <-- this opens
the file
here and
leaves it
open
{
var lineCount = File.ReadLines("fileB").Count(); <-- this tries to open it,
read it and close it..
but it can't because
you have it open
above..
This part opens fileB two times:
using (StreamReader readColour = new StreamReader("fileB"))
{
var lineCount = File.ReadLines("fileB").Count();
Try adding the line readColour.Close(); in between your read and write sections

How to create a generic text file parser for any find of text file?

Want to create a generic text file parser in c# for any find of text file.Actually i have 4 application all 4 getting input data from txt file format but text files are not homogeneous in nature.i have tried fixedwithdelemition.
private static DataTable FixedWidthDiliminatedTxtRead()
{
string[] fields;
StringBuilder sb = new StringBuilder();
List<StringBuilder> lst = new List<StringBuilder>();
DataTable dtable = new DataTable();
ArrayList aList;
using (TextFieldParser tfp = new TextFieldParser(testOCC))
{
tfp.TextFieldType = FieldType.FixedWidth;
tfp.SetFieldWidths(new int[12] { 2,25,8,12,13,5,6,3,10,11,10,24 });
for (int col = 1; col < 13; ++col)
dtable.Columns.Add("COL" + col);
while (!tfp.EndOfData)
{
fields = tfp.ReadFields();
aList = new ArrayList();
for (int i = 0; i < fields.Length; ++i)
aList.Add(fields[i] as string);
if (dtable.Columns.Count == aList.Count)
dtable.Rows.Add(aList.ToArray());
}
}
return dtable;
}
but i feel its very rigid one and really varies application to application making it configgurable .any better way ..
tfp.SetFieldWidths(new int[12] { 2,25,8,12,13,5,6,3,10,11,10,24 });
File nature :
Its a report kind of file .
position of columns are very similar
row data of file id different .
I get this as a reference
http://www.codeproject.com/Articles/11698/A-Portable-and-Efficient-Generic-Parser-for-Flat-F
any other thoughts ?
If the only thing different is the field widths, you could just try sending the field widths in as a parameter:
private static DataTable FixedWidthDiliminatedTxtRead(int[] fieldWidthArray)
{
string[] fields;
StringBuilder sb = new StringBuilder();
List<StringBuilder> lst = new List<StringBuilder>();
DataTable dtable = new DataTable();
ArrayList aList;
using (TextFieldParser tfp = new TextFieldParser(testOCC))
{
tfp.TextFieldType = FieldType.FixedWidth;
tfp.SetFieldWidths(fieldWidthArray);
for (int col = 1; col < 13; ++col)
dtable.Columns.Add("COL" + col);
while (!tfp.EndOfData)
{
fields = tfp.ReadFields();
aList = new ArrayList();
for (int i = 0; i < fields.Length; ++i)
aList.Add(fields[i] as string);
if (dtable.Columns.Count == aList.Count)
dtable.Rows.Add(aList.ToArray());
}
}
return dtable;
}
If you will have more logic to grab the data, you might want to consider defining an interface or abstract class for a GenericTextParser and create concrete implementations for each other file.
Hey I made one of these last week.
I did not write it with the intentions of other people using it so I appologize in advance if its not documented well but I cleaned it up for you. ALSO I grabbed several segments of code from stack overflow so I am not the original author of several pieces of this.
The places you need to edit are the path and pathout and the seperators of text.
char[] delimiters = new char[]
So it searches for part of a word and then grabs the whole word. I used a c# console application for this.
Here you go:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace UniqueListofStringFinder
{
class Program
{
static void Main(string[] args)
{
string path = #"c:\Your Path\in.txt";
string pathOut = #"c:\Your Path\out.txt";
string data = "!";
Console.WriteLine("Current Path In is set to: " + path);
Console.WriteLine("Current Path Out is set to: " + pathOut);
Console.WriteLine(Environment.NewLine + Environment.NewLine + "Input String to Search For:");
Console.Read();
string input = Console.ReadLine();
// Delete the file if it exists.
if (!File.Exists(path))
{
// Create the file.
using (FileStream fs = File.Create(path))
{
Byte[] info =
new UTF8Encoding(true).GetBytes("This is some text in the file.");
// Add some information to the file.
fs.Write(info, 0, info.Length);
}
}
System.IO.StreamReader file = new System.IO.StreamReader(path);
List<string> Spec = new List<string>();
using (StreamReader sr = File.OpenText(path))
{
while (!file.EndOfStream)
{
string s = file.ReadLine();
if (s.Contains(input))
{
char[] delimiters = new char[] { '\r', '\n', '\t', ')', '(', ',', '=', '"', '\'', '<', '>', '$', ' ', '#', '[', ']' };
string[] parts = s.Split(delimiters,
StringSplitOptions.RemoveEmptyEntries);
foreach (string word in parts)
{
if (word.Contains(input))
{
if( word.IndexOf(input) == 0)
{
Spec.Add(word);
}
}
}
}
}
Spec.Sort();
// Open the stream and read it back.
//while ((s = sr.ReadLine()) != null)
//{
// Console.WriteLine(s);
//}
}
Console.WriteLine();
StringBuilder builder = new StringBuilder();
foreach (string s in Spec) // Loop through all strings
{
builder.Append(s).Append(Environment.NewLine); // Append string to StringBuilder
}
string result = builder.ToString(); // Get string from StringBuilder
Program a = new Program();
data = a.uniqueness(result);
int i = a.writeFile(data,pathOut);
}
public string uniqueness(string rawData )
{
if (rawData == "")
{
return "Empty Data Set";
}
List<string> dataVar = new List<string>();
List<string> holdData = new List<string>();
bool testBool = false;
using (StringReader reader = new StringReader(rawData))
{
string line;
while ((line = reader.ReadLine()) != null)
{
foreach (string s in holdData)
{
if (line == s)
{
testBool = true;
}
}
if (testBool == false)
{
holdData.Add(line);
}
testBool = false;
// Do something with the line
}
}
int i = 0;
string dataOut = "";
foreach (string s in holdData)
{
dataOut += s + "\r\n";
i++;
}
// Write the string to a file.
return dataOut;
}
public int writeFile(string dataOut, string pathOut)
{
try
{
System.IO.StreamWriter file = new System.IO.StreamWriter(pathOut);
file.WriteLine(dataOut);
file.Close();
}
catch (Exception ex)
{
dataOut += ex.ToString();
return 1;
}
return 0;
}
}
}
private static DataTable FixedWidthTxtRead(string filename, int[] fieldWidths)
{
string[] fields;
DataTable dtable = new DataTable();
ArrayList aList;
using (TextFieldParser tfp = new TextFieldParser(filename))
{
tfp.TextFieldType = FieldType.FixedWidth;
tfp.SetFieldWidths(fieldWidths);
for (int col = 1; col <= fieldWidths.length; ++col)
dtable.Columns.Add("COL" + col);
while (!tfp.EndOfData)
{
fields = tfp.ReadFields();
aList = new ArrayList();
for (int i = 0; i < fields.Length; ++i)
aList.Add(fields[i] as string);
if (dtable.Columns.Count == aList.Count) dtable.Rows.Add(aList.ToArray());
}
}
return dtable;
}
Here's what I did:
I built a factory for the type of processor needed (based on file type/format), which abstracted the file reader.
I then built a collection object that contained a set of triggers for each field I was interested in (also contained the property name for which this field is destined). This settings collection is loaded in via an XML configuration file, so all I need to change are the settings, and the base parsing process can react to how the settings are configured. Finally I built a reflection wrapper wherein once a field is parsed, the corresponding property on the model object is set.
As the file flowed through, the triggers for each setting evaluated each lines value. When it found what it was set to find (via pattern matching, or column length values) it fired and event that bubbled up and set a property on the model object. I can show some pseudo code if you're interested. It needs some work for efficiency's sake, but I like the concept.

search line of text for EACH item returned by split in c#

I'm trying to read my apache log and do some processing with it. I use a string split function which contains log lines which refer to me in so way. I want to remove those lines. The code below shows that I've got. It only removes "127.0.0.1" but all the "192.168.1.x" lines appear.
How do I remove EVERY split string?
public void GetTheLog()
{
string path = "c:\\program files\\Zend\\apache2\\logs\\access.log";
string path2 = #"access.log";
int pos;
bool goodline = true;
string skipIPs = "127.0.0.1;192.168.1.100;192.168.1.101;192.168.1.106;67.240.13.70";
char[] splitchar = { ';' };
string[] wordarray = skipIPs.Split(splitchar);
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
StreamReader reader = new StreamReader(fs);
TextWriter tw = new StreamWriter(path2);
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
// initialize goodline for each line of reader result
goodline = true;
for (j = 0; j < wordarray.Length; j++)
{
pos = -10;
srch = wordarray[j];
ln = line.Substring(0,srch.Length);
pos = ln.IndexOf(srch);
if (pos >= 0) goodline = false;
}
if (goodline == true)
{
tw.WriteLine(line);
listBox2.Items.Add(line);
}
}
// Clean up
reader.Close();
fs.Close();
listBox1.Items.Add(path2);
tw.Close();
}
var logPath = #"c:\program files\Zend\apache2\logs\access.log";
var skipIPs = "127.0.0.1;192.168.1.100;192.168.1.101;192.168.1.106;67.240.13.70";
var filters = skipIPs.Split(';');
var goodlines = File.ReadLines(logPath)
.Where(line => !filters.Any(f => line.Contains(f)));
Then you can
File.WriteAllLines(#"access.log", goodlines);
And it also looks like you're dumping the lines into a listbox
listBox2.Items.AddRange(goodlines.Select(line=> new ListItem(line)).ToArray());
Also, since your skipIPs are just a static string, you could refactor a little and just do
var filters = new []{"127.0.0.1","192.168.1.100","192.168.1.101",...};
arrrrrr din get what you want...
okh let me try if you want to remove all the IPs which are present in your skipIPs from your current file.
then you can simply use....
if(ln==srch)
{
goodline = false;
}
instead of
pos = ln.IndexOf(srch);
if (pos >= 0) goodline = false;
inside your for loop.
hope it will jelp you... :)

Unable to open CSV file from internet using C#

I'm new with C#. I've written code to open a CSV file from my documents on my local machine. It works well and the data parsing works. Trouble is when I change the code to open the file from an internet site I cannot get it to work. I am able to open this file using VBA but I now want to use C# ADO.NET. I cannot find the answer by searching with Google. Can anyone help with the code and/or point me to a website with a good tutorial. All help much appreciated. Code attached, I'm sure the problem is with lines 24 - 26;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
//
// Read in a file line-by-line, and store it all in a List.
//
int i = 0;
DateTime dte;
List<string> list = new List<string>();
float[] Prices = new float[4];
WebClient wc = new WebClient();
byte[] data = wc.DownloadData("http://www.datasource.com/apps/qt/csv/pricehistory.ac?section=yearly_price_download&code=XXX");
using (StreamReader reader = new StreamReader(wc))
{
string line;
while ((line = reader.ReadLine()) != null)
{
//list.Add(line); // Add to list.
Console.WriteLine(line); // Write to console.
string[] parts = line.Split(',');
int DateSetter = 1;
int DateDone = 0;
int CountFloat = 0;
int PricesDone = 0;
Double Volume = 0;
foreach (string part in parts)
{
Console.WriteLine("{0} : {1}", i, part);
if (DateSetter == 1)
{
dte = DateTime.Parse(part);
DateSetter = 2;
Console.WriteLine(dte);
}
if (DateDone == 1)
{
if (DateSetter < 6)
{
Prices[CountFloat] = float.Parse(part);
CountFloat++;
DateSetter++;
Console.WriteLine(Prices[3]);
}
}
DateDone = 1;
if (PricesDone == 1)
{
Volume = double.Parse(part);
Console.WriteLine(Volume);
}
if (DateSetter == 6)
{
PricesDone = 1;
}
}
}
}
Console.ReadLine();
}
}
}
Your code as pasted would not compile. You can however use the WebClient to download to a string, then split the string into lines:
string content;
using(WebClient wc = new WebClient())
content = wc.DownloadString("http://www.datasource.com/apps/qt/csv/pricehistory.ac?section=yearly_price_download&code=XXX");
foreach(var line in content.Split(new string [] {Environment.NewLine}, StringSplitOptions.None))
{
//...
}
Another option is to download data as you're doing, and then wrap it with a MemoryStream:
WebClient wc = new WebClient();
byte[] data = wc.DownloadData(
"http://www.datasource.com/apps/qt/csv/pricehistory.ac?section=yearly_price_download&code=XXX");
using (var ms = new MemoryStream(data))
{
using (var reader = new StreamReader(ms))
{
string line;
while ((line = reader.ReadLine()) != null)
{
// do whatever
}
}
}
The advantage of this over splitting the string is that it uses considerably less memory.

Reading in files that contain specific characters in C#

I have a text file named C:/test.txt:
1 2 3 4
5 6
I want to read every number in this file using StreamReader.
How can I do that?
Do you really need to use a StreamReader to do this?
IEnumerable<int> numbers =
Regex.Split(File.ReadAllText(#"c:\test.txt"), #"\D+").Select(int.Parse);
(Obviously if it's impractical to read the entire file in one hit then you'll need to stream it, but if you're able to use File.ReadAllText then that's the way to do it, in my opinion.)
For completeness, here's a streaming version:
public IEnumerable<int> GetNumbers(string fileName)
{
using (StreamReader sr = File.OpenText(fileName))
{
string line;
while ((line = sr.ReadLine()) != null)
{
foreach (string item in Regex.Split(line, #"\D+"))
{
yield return int.Parse(item);
}
}
}
}
using (StreamReader reader = new StreamReader(stream))
{
string contents = reader.ReadToEnd();
Regex r = new Regex("[0-9]");
Match m = r.Match(contents );
while (m.Success)
{
int number = Convert.ToInt32(match.Value);
// do something with the number
m = m.NextMatch();
}
}
Something like so might do the trick, if what you want is to read integers from a file and store them in a list.
try
{
StreamReader sr = new StreamReader("C:/test.txt"))
List<int> theIntegers = new List<int>();
while (sr.Peek() >= 0)
theIntegers.Add(sr.Read());
sr.Close();
}
catch (Exception e)
{
//Do something clever to deal with the exception here
}
Solution for big files:
class Program
{
const int ReadBufferSize = 4096;
static void Main(string[] args)
{
var result = new List<int>();
using (var reader = new StreamReader(#"c:\test.txt"))
{
var readBuffer = new char[ReadBufferSize];
var buffer = new StringBuilder();
while ((reader.Read(readBuffer, 0, readBuffer.Length)) > 0)
{
foreach (char c in readBuffer)
{
if (!char.IsDigit(c))
{
// we found non digit character
int newInt;
if (int.TryParse(buffer.ToString(), out newInt))
{
result.Add(newInt);
}
buffer.Remove(0, buffer.Length);
}
else
{
buffer.Append(c);
}
}
}
// check buffer
if (buffer.Length > 0)
{
int newInt;
if (int.TryParse(buffer.ToString(), out newInt))
{
result.Add(newInt);
}
}
}
result.ForEach(Console.WriteLine);
Console.ReadKey();
}
}
I might be wrong but with StreamReader you cannot set delimeter.
But you can use String.Split() to set delimeter (it is space in your case?) and extract all numbers into separate array.
Something like this ought to work:
using (var sr = new StreamReader("C:/test.txt"))
{
var s = sr.ReadToEnd();
var numbers = (from x in s.Split('\n')
from y in x.Split(' ')
select int.Parse(y));
}
Something like this:
using System;
using System.IO;
class Test
{
public static void Main()
{
string path = #"C:\Test.txt";
try
{
if( File.Exists( path ) )
{
using( StreamReader sr = new StreamReader( path ) )
{
while( sr.Peek() >= 0 )
{
char c = ( char )sr.Read();
if( Char.IsNumber( c ) )
Console.Write( c );
}
}
}
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
}
}

Categories