无法打开c#中包含空格的文件/目录
本文关键字:空格 文件 目录 包含 | 更新日期: 2023-09-27 18:16:13
我正在创建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);
}
}
}
}
}
用using
语句包装StreamWriter
对象:
using(var file = new System.IO.StreamWriter(val_input_file_name))
{
file.WriteLine("Testing done" + val_input_file_name);
}