Read and write existing xml file trouble !

Hi everyone ! 
i'm trying to save hight score of user in my game by using a xml file , in my xml file has element <best_score>0<best_score/>
and my code to do it is : 
 XElement best=XElement.Load("Assets/best.xml");
            IEnumerable<XElement> loc = best.Elements("best_score");
            foreach (XElement elem in loc)
                int check=Convert.ToInt32(elem.Value.ToString());
                int score_user = Convert.ToInt32(scores.ToString());
                if (score_user >= check)
                   hight_score.Text = score.ToString();
                     elem.Value = scores.ToString();
                     // what code to save this  xml file  after modify ?????
                else
                    list_box.Text = check.ToString();
i down know what method can help me save my xml file after update hight score of user in this case .  
Anyone has an idea to solve it for me ? please , thanks you ! 
sorry about my english ! 

Hi,
It is not recommended to update a file withing the project, so you need to store it in the IsolatedStorage.
Here is a sample to read and write file in IsolatedStorage,
XDocument xDoc;
var file = Util.ReadFile("XMLFile.xml");
if (file != null)
xDoc = XDocument.Parse(file);
var bestScore = xDoc.Element("best_score").Value;
//do calculation
xDoc.Element("best_score").Value = "200";
Util.SaveFile("XMLFile.xml", xDoc.ToString());
For the above code to work, you need to have a file named "XMLFile.xml" in your IsolatedStorage, with data as  "<best_scrore>200</best_scrore>"
To read and write file:
public static class Util
public static void SaveFile(string filename, string data)
try
using (var store = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication())
using (var stream = new IsolatedStorageFileStream(filename, FileMode.Create, FileAccess.ReadWrite, store))
StreamWriter writer = new StreamWriter(stream);
writer.Write(data);
writer.Close();
catch (Exception)
Debug.WriteLine("Couldn't save the file.");
public static string ReadFile(string filename)
try
String data;
if (!IsolatedStorageFile.GetUserStoreForApplication().FileExists(filename)) return null;
using (var store = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication())
using (var stream = new IsolatedStorageFileStream(filename, FileMode.Open, FileAccess.ReadWrite, store))
StreamReader stmReader = new StreamReader(stream);
data = stmReader.ReadToEnd();
stmReader.Close();
return data;
catch (Exception)
return null;
Pradeep AJ

Similar Messages

  • Read and write a .CSV file contains cirillic characters issue

    Hi guys,
    I am a developer of a web application project which uses Oracle Fusion Middleware technologies. We use JDeveloper 11.1.1.4.0 as development IDE.
    I have a requirement to get a .csv file from WLS to application running machine. I used a downloadActinLinsener in front end .jspx in order to do that.
    I use OpenCSV library to read and write .csv files.
    Here is my code for read and write the .csv file,
    public void dwdFile(FacesContext facesContext, OutputStream out) {
    System.out.println("started");
    String [] nextLine;
    try {
    FileInputStream fstream1 = new FileInputStream("Downloads/filetoberead.CSV");
    DataInputStream in = new DataInputStream(fstream1);
    BufferedReader br = new BufferedReader(new InputStreamReader(in,"UTF-8"));
    CSVReader reader = new CSVReader(br,'\n');
    //CSVReader reader = new CSVReader(new FileReader("Downloads/ACTIVITY_LOG_22-JAN-13.csv"),'\n');
    List<String> list=new ArrayList();
    while ((nextLine = reader.readNext()) != null) {
    if(nextLine !=null){
    for(String s:nextLine){
    list.add(s);
    System.out.println("list size ; "+list.size());
    OutputStreamWriter w = new OutputStreamWriter(out, "UTF-8");
    CSVWriter writer = new CSVWriter(w, ',','\u0000');
    for(int i=0;i<list.size();i++){
    System.out.println("list items"+list.get(i));
    String[] entries = list.get(i).split(",");
    writer.writeNext(entries);
    //System.out.println("list items : "+list.get(i));
    writer.close();
    } catch (IOException e) {
    e.printStackTrace();
    say the filetoberead.CSV contains following data,
    0,22012013,E,E,ASG,,O-0000,O,0000,100
    1,111211,LI,0,TABO,B,M002500003593,,,К /БЭ60072715/,КАРТЕНБАЙ
    2,07,Balance Free,3
    1,383708,LI,0,BDSC,B,НЭ63041374,,,Т /НЭ63041374/,ОТГОНБААТАР
    2,07,Balance Free,161
    It reads and writes the numbers and english characters correct. All cirillic characters it prints "?" as follows,
    0,22012013,E,E,ASG,,O-0000,O,0000,100
    1,111211,LI,0,TABO,B,M002500003593,,,? /??60072715/,?????????
    2,07,Balance Free,3
    1,383708,LI,0,BDSC,B,??63041374,,,? /??63041374/,???????????
    2,07,Balance Free,161
    can somone please help me to resolve this problem?
    Regards !
    Sameera

    Are you sure that the input file (e.g. "Downloads/filetoberead.CSV") is in UTF-8 character set? You can also check it using some text editor having a view in hex mode. If each Cyrillic character in your input file occupies a single byte (instead of two), then the file is not in UTF-8. Most probably it is in Cyrillic for Windows (CP1251).
    If this is the case, you should modify the line
    BufferedReader br = new BufferedReader(new InputStreamReader(in,"UTF-8"));toBufferedReader br = new BufferedReader(new InputStreamReader(in,"windows-1251"));Dimitar

  • How do I read and write to text files on a remote computer's hard drive

    I would like to read and write data to a text file on a remote computer. This is easily accomplished using one of the file functions such as "write characters to file.vi". If I am already connected to the remote computer, all I need to do is specify the path to the particular file and it will work fine.
    My problem is that I want to connect to the remote computer programatically within LabVIEW (I do not want to have to use the computer's OS to establish the connection. Is there a function that I can use to do this?
    Thomas D. Schaefer
    Wells Manufacturing Corp

    Yariv,
    You should really start a new thread with a new question like this, so that more people see it. Some people look primarily at threads that have no responses yet. Also, don't post the exact same question in multiple places. Or, if you must cross-post to some other forum, make sure to mention it in your question text.
    I'm happy to be a brick in your Western Wall, but I'm not sure what the main objective is here. Is the main problem really getting access to the "X bytes received in Y seconds at Z bytes/sec" string? Or is it accomplishing the file transfer? And what OS and LabVIEW version are you running?
    I think your problem is that you the LabVIEW System Exec command does not allow for the degree of interactivity that you need if you want to issue a sequence of commands to a command-line executable. However, under Windows XP (and, presumably, other Windows versions, though I can't check), you can tell the FTP executable to use commands from a textfile script by using the -s switch, and you can override the prompts during multiple file transfers with the -i switch:
    ftp -i -s:FILEPATH SERVERNAME
    If you issue a command in this format to System Exec, and make sure to create a file at FILEPATH with your command sequence (one per line), then you should at least accomplish the FTP actions. This won't give you the transfer details in the standard output, unfortunately. However, if you just want a general sense of how much was transferred and how quickly it happened, you can code that in LabVIEW by getting the resulting file sizes and using Tick Count before and after the System Exec call to see how long the transfer took.
    Hope that helps,
    John

  • Is it possible to read and write to a file at the same time and display the results in a RichTextBox?

    Hi All,
    I have a purpose in winforms to have a "notepad like" editor that saves what ever i type to a file on the hard drive and reads from based. 
    So what i have is a tab with a richtextbox docked to fill. I would like to have that richtextbox read from a file on the hard drive, then save the changes i type when i either click off the tab or live if possible.
    I wills state that i am fairly new to the c# game and if this is possible and someone could post an example that would be awesome and totally appreciated.
    Thanks,
    jAC

    For those that are looking for the solution I went with here are the details
    Reading the file:
    // Wish List Section
    wishListRichTextBox.ResetText();
    string wlFolder = Application.StartupPath + "\\wishLists\\";
    string wlPath = wlFolder + selectedProduct + ".rtf";
    // Read from the text file and out put the results
    try
    { // create directory if it does not exist
    if (!Directory.Exists(wlFolder))
    Directory.CreateDirectory(wlFolder);
    } // create file if it does not exist
    if (!File.Exists(wlPath))
    File.Create(wlPath).Dispose();
    var iStream = new FileStream(wlPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
    var sr = new System.IO.StreamReader(iStream);
    var readData = sr.ReadToEnd();
    wishListRichTextBox.Text = readData;
    sr.Close();
    // If the read fails then output the error message in the same section
    catch (Exception ex)
    wishListRichTextBox.Text = "Error: " + ex.Message;
    Writing the file:
    private void wishlistTabChanged(object sender, EventArgs e)
    if(menuTabControl.SelectedTab != wishListTab){
    if (productComboBox.SelectedIndex >= 0)
    try
    string wlFolder = Application.StartupPath + "\\wishLists\\";
    string wlPath = wlFolder + productComboBox.SelectedItem + ".rtf";
    var oStream = new FileStream(wlPath, FileMode.Open, FileAccess.Write, FileShare.Read);
    oStream.SetLength(0);
    var sw = new System.IO.StreamWriter(oStream);
    sw.WriteLine(wishListRichTextBox.Text);
    sw.Close();
    catch (Exception ex)
    MessageBox.Show("Wish list for " + productComboBox.Text + " save failed. \n\nError: " +
    ex, "Wish List Save Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
    I mainly used Ammar.Zaied thought
    process on this. Thanks to everyone though, as you all pointed me in the right direction

  • How to retrieve characters like '£' from the database and write to xml file

    Hi ,
    I have a requirement to retrieve the data from database and write to files in XML format.
    I am able to do so successfuly by using XMLElement tag and writing to file through UTL_File package.
    All characters like <&@^ get converted properly, but when it comes to multibyte chars like '£', they are not able to get converted as it is.
    Can somebody please advise me how to go ahead.
    Regards

    Thanks odie.
    The nls_charset for my database is WE8ISO8859P1 and database version is Oracle Database 10g Enterprise Edition Release 10.2.0.5.0 - 64bi.
    The data (with pound sign) is sitting in one of the columns of the table and when i query it directly, I am able to view it properly.
    However when I use the below code to retrieve in XML format and print it to file, it gets changed. This file is also passed to one of the application GUI where this XML gets processsed and it is not visible properly.
    below id the sample abstract of code I am using.
    Declare
    l_file UTL_FILE.FILE_TYPE;
    l_clob CLOB;
    l_buffer VARCHAR2(32767);
    l_amount BINARY_INTEGER := 32767;
    l_pos INTEGER := 1;
    Begin
    SELECT XMLElement("case",
    XMLElement("comments",
    XMLElement("comment",
    XMLElement("comments",a.COMMENTS)
    ).getClobVal() val1 into l_clob
    FROM TO_COMMENTS a
    l_file :=
    UTL_FILE.fopen (XMLDIR,
    test.xml,
    'w',
    32767);
    LOOP
    DBMS_LOB.read (l_clob,
    l_amount,
    l_pos,
    l_buffer);
    UTL_FILE.put_line (l_file, l_buffer);
    l_pos := l_pos + l_amount;
    END LOOP;
    EXCEPTION
    WHEN NO_DATA_FOUND THEN
    DBMS_OUTPUT.NEW_LINE('Reached end of file');
    END;
    The comments column given contains the character like pound.
    And once the file is generated and i see using the vi editor, the char is not viewable properly like £
    And when the same is passed to GUI application to be processed, its not viewable propely in GUI from IE as well like �.

  • Read and write into csv file using procedure

    I would like to read a particular column value from csv file(which will have many columns) using procedure and for that value I have to retrieve some more values from database table and have to append into same csv file.
    can someone help me?
    Thanks
    Edited by: 1002478 on Apr 25, 2013 5:52 AM
    Edited by: 1002478 on Apr 25, 2013 5:55 AM

    1002478 wrote:
    thanks for your reply.
    Using UTL_FILE i'm able to read csv file. I'm stuck up in appending some more columns to same csvYou'll struggle to append data to an existing CSV.
    You'd be better to read the data from one CSV, and create another CSV using that data, and the extra data you want, and then when finished, delete the original file and rename the new file to the old filename.
    You should be able to do that using External Tables to read the source file (easier than using UTL_FILE) and UTL_FILE to write the new file.

  • How to read and write from XL file

    HI ,
    I wanted to read a data from XL file and write a data in XL file by generating a report .Can any body help me out.Many examples are available on discussion forums but when I try to save and run those Vi .I am not able to run Showing error .Please tell what is going wrong as I m having latest labview 8.6 .
    Regards
    Sharmila.karale

    Hi Adnan,
    Here are the examples of Vi which I have downloaded from the forum for my reference
    Regards
    Sharmila.Krale
    Attachments:
    SAVE TO EXCEL.llb ‏128 KB
    excel.llb ‏1618 KB

  • How to install tamil fonts to read and write non pdf files

    Hi,
       i bought a new mac book pro...i want to edit my documents which are typed in vanavil avvaiyar a tamil font...but i dont know how to install it..and i hav a duobt that whether this mac may support tamil fonts in mac office.....

    The Mac supports Tamil input Method and lists Anjal and Tamil99.
    Microsoft Office probably does not.

  • I have an excel file,i want to read and write this file to xml

    hello,
    i have an excel file,i want to read excel data and write to xml file .i also have an exisitng xml file and i want to appened the excel data to the exisiting xml.please give some example code.
    thanks

    GoOgLe

  • How read and write file

    Hi
    please help me
    How to read and write data from file in j2me

    hello, u are looking to write some persistant data to a file on the mobile phone? Its the next step for me aswell. You can use the recordset function.
    I'm looking at this site: http://www-128.ibm.com/developerworks/library/wi-rms/
    It seems every time you use the function you must use try catch blocks. I hope this is what you are looking for.

  • Reading and writing from a file

    I am trying to read and write to a file so that I may store an array of string and a double in my application, but I have come upon a couple of problems; first when I put my file path into the path constant it will say that the file is not there ever though it is (so I have to force the issue and when the application asks for a file I have to browse and add the files), secondly when I run the program and it reads from the file it does not display the strings or doubles immediately instead I have to hit the submit button and than they finally come up, thirdly when I reset my values in the .txt files and put in my string and double and hit submit the array jumps one spot and starts at the index of 1 (array[1])  if anyone can help I would appreciate it a lot.
    here is my code:
    Harold Timmis
    [email protected]
    Orlando,Fl
    *Kudos always welcome
    Solved!
    Go to Solution.
    Attachments:
    testingfileIO.vi ‏30 KB
    double.txt ‏1 KB
    string.txt ‏1 KB

    Harold Timmis wrote:
    I am trying to read and write to a file so that I may store an array of string and a double in my application, but I have come upon a couple of problems; first when I put my file path into the path constant it will say that the file is not there ever though it is (so I have to force the issue and when the application asks for a file I have to browse and add the files),
    I don't see that behavior at all about forcing the issue.  Why are you using Not a Path constants?  Why not turn those constants into controls you put on your front panel?
    secondly when I run the program and it reads from the file it does not display the strings or doubles immediately instead I have to hit the submit button and than they finally come up,
    Put your array indicators before your event structure rather than after.  Think dataflow.  The code pauses at the event structure waiting for an even to fire.  Only when it does (such as hitting the submit button) does the data get written to the array indicators. 
    thirdly when I reset my values in the .txt files and put in my string and double and hit submit the array jumps one spot and starts at the index of 1 (array[1])  if anyone can help I would appreciate it a lot.
    I don't see this behavior either.  How come your double.txt file has names in it, and your string.txt file has doubles in it?

  • How to read and write data from json file from windows phone7 app

    Hi
    I am developing wp7 app for the use of students my questions are
    How can i write a code to read and write the json/text file for the wp7.
    I am using windows 7 OS, VS 2010 Edition.
    This is my code below:
    xaml:
    <Grid>
                        <TextBlock Height="45" HorizontalAlignment="Left" Margin="7,18,0,550" Name="textBlock1" Text="Full
    Name: " />
                        <TextBox Width="350" Height="70" HorizontalAlignment="Left" Margin="108,1,0,0" Name="txtName"
    Text="Enter your full name" VerticalAlignment="Top" />
                        <TextBlock Height="45" HorizontalAlignment="Left" Margin="6,75,0,0" Name="textBlock2" Text="Contact
    No: " VerticalAlignment="Top" />
                        <TextBox Width="350" Height="70" HorizontalAlignment="Left" Margin="108,61,0,480" Name="txtContact"
    Text="Enter your contact number" MaxLength="10" />
                        <Button Content="Register" Height="72" HorizontalAlignment="Left" Margin="10,330,0,0" Name="btnRegister"
    VerticalAlignment="Top" Width="190" Click="btnRegister_Click" />
                    </Grid>
    xaml.cs:
    private void btnRegister_Click(object sender, RoutedEventArgs e)
                string name, contact;
                name = txtName.Text;
                contact = txtContact.Text;
                try
                    if (name != "" && contact != "")
                        string msg = name + " " + contact;
                        MessageBox.Show(msg);
                        Student stud = new Student
                            Name= name,
                            Contact = contact,
                        string jsonString = JsonConvert.SerializeObject(stud);
                        MessageBox.Show(jsonString);
                    else
                        MessageBox.Show("Input Proper Information", MessageBoxButton.OK);
                catch (Exception ex)
                    MessageBox.Show(ex.Message);
    I have download NewtonSoft.json version 5.0.8.
    So, I am able to convert input data into json format, but how can I able to write and read this data from a json/text file.
    How can I do?
    Thank you in adv and please, reply soon.

    We don't have many samples left for Windows Phone 7 + Azure, the closest one to what you want to do is probably:
    Using Local Storage with OData on Windows Phone To Reduce Network Bandwidth
    this sample uses the local database feature: 'LINQ to SQL', available to Windows Phone 7.1 and 8.0 Silverlight applications, instead of simple file storage but even if you choose to stick with simple file storage I believe you should be able to adapt the
    networking related portions of the sample to your particular application.
    Eric Fleck, Windows Store and Windows Phone Developer Support. If you would like to provide feedback or suggestions for future improvements to the Windows Phone SDK please go to http://wpdev.uservoice.com/ where you can post your suggestions and/or cast
    your votes for existing suggestions.

  • How to read and write files using flex?

    Using flex, we would like to make some utility that will do a
    lot of reading and writing from local files.
    The writing is what I am more worried about. How is this
    possible?
    I want to make .zip files containing many xml files, and some
    assorted media files such as .swf jpeg, html, etc.
    I am new to flex btw, I've never used it properly before, and
    this is the main concern I have with flex, which is that it doesn't
    let me write and read lots of files.
    Mainly we are looking for a good cross platform solution that
    will let us develop an app, and flex looks professional and it is
    cross platform. The "internet app" side of things, isn't so much
    what we need really.
    Would wxWidgets be better suited to our needs?

    The Flash player sand box will not allow reading and writing
    local files. If you want to use Flex to create a desktop you will
    need the Apollo runtime. The alpha is available at Adobe
    Labs.

  • Read and Write iDVD trouble with backed up iDVD project

    Hey guys, I need to open an iDVD project file within my time machine backups for a previously existing user on an external backup hard drive.
    When I click it to open I get this message: "An error occurred while loading the project. This project seems to be write-protected and can't be opened."
    I've tried right clicking on the file, selecting 'Get info' and changing administrators and 'everyone' to read and write but no luck. Any ideas, suggestions would be greatly appreciated! Thanks!

    Correct.
    Now I see I missed the wording of the "file not writeable" message, which doesn't sound like a permissions issue. That sounds like it's either not compatible (ie, not for the same version of iDVD), or corrupted.
    If you haven't changed versions, try a +*Verify Disk+* on your internal HD, per #A5 in [Time Machine - Troubleshooting|http://web.me.com/pondini/Time_Machine/Troubleshooting.html] (or use the link in *User Tips* at the top of this forum).

  • Read and Write Excel File

    Hi all. I need your need help. I need to know how to read EXCEL FILE and insert it to a certain table. By the way, can anyone tell me how to write to a EXCEL FILE?
    Thank you in advance.

    READING EXCEL
    There are several options how to read excel file - ODBC, on a fly excel-->CSV conversion (if you have 11.2 and want to use external tables preprocessor), ... I put (I think all) options on my BLOG http://jiri.wordpress.com/2010/01/04/load-ms-excel-file-to-oracle-database/
    WRITING TO EXCEL
    Writing to excel is tricky because there is no direct way from Oracle, here are few tips
    1. JAVA - you can create java stored procedure, I did not test this but it's probably doable http://www.java-tips.org/other-api-tips/jexcel/how-to-create-an-excel-file.html
    2. Excel XML format - you can use UTL_FILE and write to XML format Excel can read http://blogs.msdn.com/b/brian_jones/archive/2005/06/27/433152.aspx
    3. Excel can also read CSV files, but it's plan text file with no formatting. You can use UTL_FILE to easily create CSV (comma separated) file and read it from excel, I have few samples on my blog http://jiri.wordpress.com/2009/03/18/oracle-fast-parallel-data-unload-into-ascii-files/

Maybe you are looking for

  • If statement is not validating properly in JSP

    Actually i'm new to Java.. The problem is when i take the parameter from another file which is an empty text box and i submit that. In the next jsp file i'am taking this value using getParameter("xxxx"). if i send the empty or some value to this para

  • How can I turn off Privacy in iOS 8.2

    HHow do I make my ipad2 work normally again after updating to iOS 8.2.  How can I turn the privacy off.  Thank you Teresa

  • Is it possible to run a command when a monitor goes to a healthy state?

      Hi,  I'm using SCOM 2007R2 Is it possible to run a command/script when a web application Monitor changes to a healthy state? I have a web application monitor that checks four different websites from our proxy servers.  on the aggregate rollup of al

  • Function module 'SO_NEW_DOCUMENT_ATT_SEND_API1' not sending detail in email

    Hello experts, I am using function module 'SO_NEW_DOCUMENT_ATT_SEND_API1' to send emails from a workflow method. The emails are being sent out and received but there is no detail in the email. The following are my parameters. CALL FUNCTION 'SO_NEW_DO

  • Accessing icloud website via mobile?

    I want to access iCloud's data on the actual web page. You know, where I can change things about my contacts and mail and such and everything. But I'm too lazy at times to get up and download icloud onto my PC. Every time I try and access the icloud