how to read .txt file into string windows 6 classic / windows CE, using vs2005?

494 Views Asked by At

iam creating an app for a handheld with windows embedded handheld 6.5, iam stuck with reading the content of text file and loading into a string. the file is tab delimeted with 3 columns (barcode, desc, price).the code will be executed on form load, i have written the below using c# on vb2005 releasing on windows 6 classic emulator, but the streamreader is always null. i have written the below please any advices, i appreciate the help!

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

private void Form1_Load(object sender, EventArgs e)
{
    string fileloc = "fileexample.txt";               
    StreamReader sr = new StreamReader(fileloc);
    string s = sr.ReadToEnd();                   
}
4

There are 4 best solutions below

0
Youssef Shaaban On

Try use

File.ReadAllText("Full File Path");

and use the Full file path like C:\fileexample.txt

5
paulsm4 On

OK:

How can I read all text when ReadAllText is unavailable?

The compact-framework edition does not implement it. The .net version, however, is simply implemented like this:

public static class File
{
    public static String ReadAllText(String path)
    {
        using (var sr = new StreamReader(path, Encoding.UTF8))
        {
            return sr.ReadToEnd();
        }
    }
}

Note the second argument to StreamReader: Encoding.UTF8.

See also:

Compact Framework: A problem with reading a file

Windows CE doesn't have the concept of "current directory". The OS tries to open \list.txt when passing "list.txt". You always have to specify the full path to the file. ...

In full framework I use:

string dir = Path.GetDirectory(Assembly.GetExecutingAssembly().Location);
string filename = Path.Combine(dir, "list.txt");
StreamReader str = new StreamReader(filename);

STRONG SUGGESTIONS:

  1. Specify an encoding (e.g. UTF8)
  2. Set a breakpoint in this method and single-step through your code.
1
ali On

After a long search, I found what I was looking for. I wanted to share so others would not suffer like I did:

private void Form1_Load(object sender, EventArgs e)
{
    string dir = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
    string filename = Path.Combine(dir, "alisyd.txt");
    StreamReader sr = new StreamReader(filename);
    string s = sr.ReadToEnd();          
}
0
marcxploit On
string FilePath = "/"; //Root
string FileName = "MyFile.txt";
string MyString = "";
StreamReader sr = new StreamReader(File.OpenRead(FilePath + FileName), Encoding.Default, true);
while (!sr.EndOfStream)
{
    MyString += sr.ReadLine();
}
sr.Dispose();
sr.Close();