Search code examples
c#visual-studio-2008io

Error with the command System.IO.File.WriteAllLines()


Hello i am trying to save an object that i have been created and its returning to me error: "represents as a series of Unicode character" on this line: System.IO.File.WriteAllLines(@"C:\Users\1\AppData\Roaming\MYDATA\hi.txt", somOne);

here is the code:

main class:

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Persone somOne = new Persone("bob", 5, 200);
            System.IO.Directory.CreateDirectory(@"C:\Users\1\AppData\Roaming\MYDATA");
            // the Error line Is HERE \/
            System.IO.File.WriteAllLines(@"C:\Users\1\AppData\Roaming\MYDATA\hi.txt", somOne);
        }
    }
}

persone class:

namespace ConsoleApplication1
{
    class Persone
    {
        private String name;
        private int id;
        private int age;
        public Persone(String name, int id, int age)
        {
            setName(name);
            setId(id);
            setAge(age);

        }
        public void setName(String name)
        {
            this.name = name;
        }
        public String getName()
        {
            return name;
        }
        public void setId(int id)
        {
            this.id = id;
        }
        public int getId()
        {
            return id;
        }
        public void setAge(int age)
        {
            this.age = age;
        }
        public int getAge()
        {
            return age;
        }
    }
}

do i need to chang the type of "somOne"? and how?


Solution

  • System.IO.File.WriteAllLines expects array of strings (or IEnumerable<string>) as second parameter, so code you have should not even compile. You can add to your Person class something like:

    public string[] ToStringArray()
     {
         //And put it everything you need to store
         return new[] {name, id.ToString(), age.ToString()};
     }
    

    and call like this:

    System.IO.File.WriteAllLines(@"C:\Users\1\AppData\Roaming\MYDATA\hi.txt", somOne.ToStringArray());