locked
READING FROM A LOCAL FILE RRS feed

  • Question

  • Hy guys!

     

    For two hours I'm trying to read from a file some text and put it in a textblock.

    I used FileReaders, File.OpenText(filename), OpenFileDialog,  every thing that I can to make it work and still nothing.....

    All sorts off errors appear and the fact is they look like they appear because the file cannot be found . I included the file, Adding An existing file or Adding a new file ....

     Please help !

     

    Thanks!

    Cosmin

    Monday, April 19, 2010 4:33 PM

Answers

  • Hi,

    Are you adding the txt file to silverlight project and want to read from it? If this is the case, please first make the build action of the file to be "Resource", and then you can use following code to read from it:

    Stream stream = Application.GetResourceStream(new Uri(@"ReadFile;component/TextFile1.txt", UriKind.RelativeOrAbsolute)).Stream;
    TextReader reader = new StreamReader(stream);
    localTxt.Text = reader.ReadLine();

    While my silverlight project name is ReadFile and I add a TextFile1.txt at the root of my project, you may want to change the uri string to yours.

    Wednesday, April 21, 2010 10:59 PM

All replies

  •  Here is an example:

     

    OpenFileDialog dlg = new OpenFileDialog();
    dlg.Multiselect = false;
    dlg.Filter = "JPEG Files (*.jpg)|*.jpg";
    bool bResult = (bool)dlg.ShowDialog();
    if (!bResult)
    return;
    FileDialogFileInfo info = dlg.SelectedFile;
    Status.Text = info.Name;
    Stream s = info.OpenRead();

    BitmapImage bi = new BitmapImage();
    bi.SetSource(s);
    Image.Source = bi;
    s.Close();
     

    This is opening a jpg and assigning it to a UI element.

    Is this similar to what you're attempting?

     

    Edit: Alternatively, here is a good overview of file access in Silverlight:

    http://www.insidercoding.com/post/2008/08/08/Tutorial-Reading-and-Writing-Files-in-Silverlight.aspx

     

    Monday, April 19, 2010 4:42 PM
  • hmm ... i'm just looking to get some text from a TextFile.txt

     

    for example, the text file could be a single line: Tomorrow i'm going to the movies...

     

    I just want to take that text and put it in a textblock...

    I saw your example earlyer when i was searching how to resolve my problem, but i''m not looking for JPG images.....

    Thanks !

    Edit: I even read the Tutorial you provided http://www.insidercoding.com/post/2008/08/08/Tutorial-Reading-and-Writing-Files-in-Silverlight.aspx
    I don't know what the problem is ...

    Monday, April 19, 2010 4:50 PM
  • Hi,

    Are you adding the txt file to silverlight project and want to read from it? If this is the case, please first make the build action of the file to be "Resource", and then you can use following code to read from it:

    Stream stream = Application.GetResourceStream(new Uri(@"ReadFile;component/TextFile1.txt", UriKind.RelativeOrAbsolute)).Stream;
    TextReader reader = new StreamReader(stream);
    localTxt.Text = reader.ReadLine();

    While my silverlight project name is ReadFile and I add a TextFile1.txt at the root of my project, you may want to change the uri string to yours.

    Wednesday, April 21, 2010 10:59 PM
  • Frank u r great. it is working fine for me. Thanks & Regards, Arul Prakash.M
    Thursday, April 22, 2010 9:28 AM
  • Frank, YOU ARE AWESOME!

    After one week of trying, I managed to read from a text file. THANK YOU SO MUCH!!!!!!

     Now all i need to do is format the text with splitter. What i mean by that is:

    let's say my file TextFile1.txt looks like this:

    1|My text file finnally works|Yeah it does|Thanks FRANK!|

    2|Now I need to format it|Don't Really Know how|Hope I find a way|

    and in the code, i would like to test the line. I have a variable int LINE which, for our example, takes either value 1, either value 2. I would like to fill some textBlocks with the corresponding texts between the "|"

    text1.Text = text between the first two "|   |" 

    text2.Text = text between the second two "|    |"

    text3.Text = text between the third two "    "

    So, in my SL application if the LINE ==1, then 

    text1.Text will be  My text file finnally works

    text2.Text will be Yeah it does

    text3.Text will be Thanks FRANK!

    or fi LINE==2

    text1.Text will be Now I need to format it

    text2.Text will be Don't Really Know how

    text3.Text will be Hope I find a way

    Any ideas ???????

    Thanks again!

    Cosmin

     

    Tuesday, April 27, 2010 4:04 PM
  • Ok, so I've managed something....

    StreamReader reader2 = new StreamReader(stream);for (int i = 0; i < ID_Line; i++)

    reader.ReadLine();

    String line = reader.ReadLine();

     

    String[] lineseparated=new String[line.Split('|').Length];

    lineseparated = line.Split('|');

    for (int i = 0; i < lineseparated.Length; i++)

    MessageBox.Show(lineseparatedIdea.ToString());

    txtQuestion.Text = lineseparated[1];

    reader.Dispose();

     The problem is, sometimes I have a new line. I tried writing in the text file the '\n' and instead of printing a new line, it actually prints the "Some Text goes \n here"

    Need to find a way to print a new line .... hmmm ????

    Any ideas ? :)

    Tuesday, April 27, 2010 4:44 PM
  • Hi,

    According to my understanding, you want to render "\n" as a line break in silverlight, right? If this is the case, you can use LineBreak. Here is my thought, when you read common text, you can add Run to TextBlock.Inlines, when you encounter a "\n", you can add a LineBreak:

    TextBlock block = new TextBlock();
    block.Inlines.Add(new Run() { Text = "This is the first line" });
    block.Inlines.Add(new LineBreak());
    block.Inlines.Add(new Run() { Text = "This is the second line" });
    Wednesday, April 28, 2010 1:21 AM
  • Frank,

    One again, A MILLION THANKS! It worked. I managed to do what I wanted to. Couldn't have done it without you!

    Thank you very much for your help, and I wish you all the best!

    Cosmin

    Wednesday, April 28, 2010 2:13 PM
  • Using this method, is it possible to make the text file dynamic?  So I can change the content in the text file and have it apply without re building the application?

    Friday, May 21, 2010 6:49 PM
  • No. If you want that functionality, you'll need to serialize it to isolated storage and modify/read it from there. I.e. first time check to see if it is in isolated storage, and if not, copy from your text file there, then moving forward, manipulate it within isolated storage.

    Monday, May 24, 2010 1:55 PM
  • No. If you want that functionality, you'll need to serialize it to isolated storage and modify/read it from there. I.e. first time check to see if it is in isolated storage, and if not, copy from your text file there, then moving forward, manipulate it within isolated storage.

     

     

     

    public class ImageSerialization
        {
    
    
    
            public Object DeserializeObject(String pXmlizedString)
            {
    
    
    
    
                XmlSerializer xs = new XmlSerializer(typeof(byte[]));
    
                MemoryStream memoryStream = new MemoryStream(StringToUTF8ByteArray(pXmlizedString));
    
                //  XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
    
    
    
                return xs.Deserialize(memoryStream);
    
            }
            private Byte[] StringToUTF8ByteArray(String pXmlString)
            {
    
                UTF8Encoding encoding = new UTF8Encoding();
    
                Byte[] byteArray = encoding.GetBytes(pXmlString);
    
                return byteArray;
    
            }
    
    
    
    
    
        }
    
    
    
    
    vusing System;
    using System.Net;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Documents;
    using System.Windows.Ink;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Animation;
    using System.Windows.Shapes;
    using System.IO;
    using System.IO.IsolatedStorage;
    using System.Xml.Linq;
    
    namespace SilverlightApplication.App_Code
    {
        public class Isolation
        {
            public void SaveData(string data, string fileName)
            {
    
                using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
                {
    
                    using (IsolatedStorageFileStream isfs = new IsolatedStorageFileStream(fileName, FileMode.Create, isf))
                    {
    
                        using (StreamWriter sw = new StreamWriter(isfs))
                        {
    
                            sw.Write(data);
    
                            sw.Close();
    
                        }
    
                    }
    
                }
    
            }
    
            public string LoadData(string fileName)
            {
    
                string data = String.Empty;
    
                using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
                {
    
                    using (IsolatedStorageFileStream isfs = new IsolatedStorageFileStream(fileName, FileMode.Open, isf))
                    {
    
                        using (StreamReader sr = new StreamReader(isfs))
                        {
    
                            string lineOfData = String.Empty;
    
                            while ((lineOfData = sr.ReadLine()) != null)
    
                                data += lineOfData;
    
                        }
    
                    }
    
                }
    
                return data;
    
            }
    
    
    
    
    
    
    
            public void isolatedstorezoomvar()
            {
                SaveData("yeszoom", "checkzoom.txt");
    
            }
    
    
    
            public void isolatedstorepan()
            {
                SaveData("yespan", "checkpan.txt");
    
            }
    
    
            public void SaveXMLData(XDocument data, string fileName)
            {
    
                using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
                {
    
                    using (IsolatedStorageFileStream isfs = new IsolatedStorageFileStream(fileName, FileMode.Create, isf))
                    {
    
                        data.Save(isfs);
    
                    }
    
                }
    
            }
            public XDocument LoadXMLData(string fileName)
            {
    
    
                XDocument xdoc;
                
                using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
                {
    
                    using (IsolatedStorageFileStream isfs = new IsolatedStorageFileStream(fileName, FileMode.Open, isf))
                    {
    
                        xdoc = XDocument.Load(isfs);
                        
                       
    
                    }
    
                }
    
                return xdoc;
    
            }
    
    
    
    
    
            public void ISoDeleteFile( string fileName)
            {
    
                using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
                {
    
                    isf.Remove();
                    
    
    
    
                }
    
            }
    
        }
    using System;
    using System.Net;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Documents;
    using System.Windows.Ink;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Animation;
    using System.Windows.Shapes;
    using System.IO;
    using System.IO.IsolatedStorage;
    using System.Xml.Linq;
    
    namespace SilverlightApplication.App_Code
    {
        public class Isolation
        {
            public void SaveData(string data, string fileName)
            {
    
                using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
                {
    
                    using (IsolatedStorageFileStream isfs = new IsolatedStorageFileStream(fileName, FileMode.Create, isf))
                    {
    
                        using (StreamWriter sw = new StreamWriter(isfs))
                        {
    
                            sw.Write(data);
    
                            sw.Close();
    
                        }
    
                    }
    
                }
    
            }
    
            public string LoadData(string fileName)
            {
    
                string data = String.Empty;
    
                using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
                {
    
                    using (IsolatedStorageFileStream isfs = new IsolatedStorageFileStream(fileName, FileMode.Open, isf))
                    {
    
                        using (StreamReader sr = new StreamReader(isfs))
                        {
    
                            string lineOfData = String.Empty;
    
                            while ((lineOfData = sr.ReadLine()) != null)
    
                                data += lineOfData;
    
                        }
    
                    }
    
                }
    
                return data;
    
            }
    
    
    
    
    
    
    
            public void isolatedstorezoomvar()
            {
                SaveData("yeszoom", "checkzoom.txt");
    
            }
    
    
    
            public void isolatedstorepan()
            {
                SaveData("yespan", "checkpan.txt");
    
            }
    
    
            public void SaveXMLData(XDocument data, string fileName)
            {
    
                using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
                {
    
                    using (IsolatedStorageFileStream isfs = new IsolatedStorageFileStream(fileName, FileMode.Create, isf))
                    {
    
                        data.Save(isfs);
    
                    }
    
                }
    
            }
            public XDocument LoadXMLData(string fileName)
            {
    
    
                XDocument xdoc;
                
                using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
                {
    
                    using (IsolatedStorageFileStream isfs = new IsolatedStorageFileStream(fileName, FileMode.Open, isf))
                    {
    
                        xdoc = XDocument.Load(isfs);
                        
                       
    
                    }
    
                }
    
                return xdoc;
    
            }
    
    
    
    
    
            public void ISoDeleteFile( string fileName)
            {
    
                using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
                {
    
                    isf.Remove();
                    
    
    
    
                }
    
            }
    
        }
    }
      
    Monday, May 24, 2010 2:08 PM
  • Hi,

    I have serialized and saved the files to database. I also saved the extention of the file. Now I need to read that file and allow the user to save it on local disk. How can I do that in Silverlight4?. My application in not OOB enabled.

     

     

    Thursday, February 3, 2011 2:01 AM
  • sorry for reviving an old thread but if anyone is kind enough to help me, I've been cracking my head trying to self learn silverlight since last week. Visit my thread below thx.

    http://forums.silverlight.net/forums/t/226645.aspx

    Friday, April 22, 2011 9:43 AM
  • Hi,

    Are you adding the txt file to silverlight project and want to read from it? If this is the case, please first make the build action of the file to be "Resource", and then you can use following code to read from it:

    Stream stream = Application.GetResourceStream(new Uri(@"ReadFile;component/TextFile1.txt", UriKind.RelativeOrAbsolute)).Stream;
    TextReader reader = new StreamReader(stream);
    localTxt.Text = reader.ReadLine();

    While my silverlight project name is ReadFile and I add a TextFile1.txt at the root of my project, you may want to change the uri string to yours.

    Hello Frank,

    I used this way but I got an Exception Error

    This is my code:

                String path = "/TestingFileReader;component/1.txt"; //1
                Uri uri = new Uri(path, UriKind.RelativeOrAbsolute); //2
                StreamResourceInfo sri = Application.GetResourceStream(uri); //3
                Stream stream = sri.Stream; //4
                TextReader reader = new StreamReader(stream); //5
                String data = reader.ReadToEnd(); //6
    The error is in line # 4: "Object reference not set to an instance of an object"
    Tuesday, February 14, 2012 2:19 PM

  • Oh Good, Now it works fine

    I wasn't able to set the Build action to "Resources" but I figured it out

    I have to go from the Solution Explorer to the text file and right-click > properties.

    Then change the build action from 'None" to "Resources"

    Hit F5 :) that's it

    Thanks Frank

    Wednesday, February 15, 2012 1:28 AM