-4

I am creating windows form application. I am unable to put the output in a file. The issue is that there is space in the path name.

I want to create a file name and write the file at below location.

C:\Documents and Settings\admin\Desktop\details.txt

Please help.

Below is the code:

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


namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {

        String val_input_file_name = textBox1.Text;

        MessageBox.Show(val_input_file_name);
        try
        {

            System.IO.StreamWriter file = new System.IO.StreamWriter(val_input_file_name);
            file.WriteLine("Testing done" + val_input_file_name);
        }

        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    private void button2_Click(object sender, EventArgs e)
    {
        openFileDialog1.Filter = "Text Files|*.txt";

        DialogResult result = openFileDialog1.ShowDialog();

        if (result == DialogResult.OK) // Test result.
        {
            try
            {
                textBox1.Text = openFileDialog1.FileName;
                MessageBox.Show(openFileDialog1.FileName);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}
}

1 Answers1

1

Wrap your StreamWriter object with a using statement:

using(var file = new System.IO.StreamWriter(val_input_file_name))
{
    file.WriteLine("Testing done" + val_input_file_name);
}
Selman Genç
  • 100,147
  • 13
  • 119
  • 184