views:

62

answers:

7

How can i do below without assign null value "Tex=null"?

   static void Main(string[] args)
        {
            FileInfo f = new FileInfo("C:/temp/Arungg.txt");
            StreamWriter Tex;
            Tex = null;
            if (!f.Exists)
            {
                f.CreateText();
            }
            else
            {
                Tex = f.AppendText();
            }
                Tex.WriteLine("Test1");
                Tex.WriteLine("Test2");
                Tex.Write(Tex.NewLine);
                Tex.Close();
                Console.WriteLine(" The Text file named Arungg is created ");


        }
+4  A: 

You need to make sure that Tex is assigned in every code path.

        if (!f.Exists)
        {
            Tex = f.CreateText();
        }

Note that the AppendText method will create the file if it doesn't exist.
Therefore, you don't need the if statement at all.

SLaks
+1  A: 
Tex = f.Exists? f.AppendText(): f.CreateText();
Jhonny D. Cano -Leftware-
+1  A: 
static void Main(string[] args)
    {
        FileInfo f = new FileInfo("C:/temp/Arungg.txt");

        StreamWriter Tex = f.Exists ? f.AppendText() : f.CreateText();

        Tex.WriteLine("Test1");
        Tex.WriteLine("Test2");
        Tex.Write(Tex.NewLine);
        Tex.Close();

        Console.WriteLine(" The Text file named Arungg is created ");
    }
Philippe Leybaert
+1  A: 

You can't. If f.Exists is false, Tex never gets set before it's used after the if-block, so you have to assign it something.

I'm also pretty sure you'll get a NullReferenceException in that case as well, so are you sure you're not just meaning to assign Tex in your if-block?

lc
A: 

If you don't instantiate your StreamWriter, it's going to bomb on you. You need to assign a value to get it to compile, but without an instance, it's not going to do what you think it will do.

Perhaps simplify and consider using File.WriteAllText?

48klocs
+2  A: 

Replace what you have with something like this.

using (StreamWriter Tex = new StreamWriter("C:/temp/Arungg.txt", true, Encoding.UTF8))
{
    Tex.WriteLine("Test1");
    Tex.WriteLine("Test2");
    Tex.Write(Tex.NewLine);
    Console.WriteLine(" The Text file named Arungg is created ");
} 

This will create the file if it does not exist or open it for appending if it does. No if necessary, no code that won't compile (as in your sample), and you get proper disposal of resources.

Anthony Pegram
`File.AppendText`
SLaks
+1  A: 

Edit: I always truncated the file :)

        var f = new FileInfo(@"c:\temp\Arungg.txt");
        var writer = f.Exists ? f.AppendText() : new StreamWriter(f.OpenWrite());
        using (writer)
        {
            writer.WriteLine("Test1");
            writer.WriteLine("Test2");
            writer.WriteLine(); // No need for NewLine
        }
simendsjo
Anthony had a better way :)
simendsjo
Perhaps, but your use of `writer.WriteLine();` was itself an improvement.
Steven Sudit