无法在C#中打开包含空格的文件/目录

时间:2014-08-04 15:05:29

标签: c#

我正在创建Windows窗体应用程序。 我无法将输出放在文件中。问题是路径名中有空格。

我想创建一个文件名并将文件写在下面的位置。

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

请帮忙。

以下是代码:

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 个答案:

答案 0 :(得分:1)

使用StreamWriter声明包裹您的using对象:

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