大家好,首先抱歉我的英语,但我希望你能理解我... 我在VS2008-Smart Device Project-WinCE 5.0 Project上做了一个项目。 我需要创建一个文本文件到DATA文件夹,它位于程序的主目录下。
有我的代码,没有错误信息,但它没有创建文本文件。我的目录总是返回null。 该代码有什么问题?
if (Form2.dosya_adi != null)
{
string cfile = Form2.chosenfile;
path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase) + "\\DATA\\" + cfile+ ".txt";
}
else
{
path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase)+"\\DATA";
}
try
{
StreamReader Read_File= File.OpenText(path);//Dosyayı açmaya çalış olmaz ise catch bloğuna geç
ReadFile.Close();
}
catch
{
StreamWriter Write_File= File.CreateText(path+ i.ToString()+".txt");// yeni dosya oluştur.
Write_File.Close();
}`
并且包含listbox和listbox的form2显示了是否存在文件的目录..
string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
path = path + "\\DATA";
DirectoryInfo di = new DirectoryInfo(path);
FileInfo[] rgFiles = di.GetFiles();
foreach (FileInfo fi in rgFiles)
{
listBox1.Items.Add(fi.Name);
}
private void button1_Click(object sender, EventArgs e)
{
if (listBox1.SelectedItem != null)
{
chosen_file = listBox1.GetItemText(listBox1.SelectedItem);
Form1 form1 = new Form1();
form1.Show();
this.Hide();
}
else
{
MessageBox.Show("HATA:Hiçbir Değer Seçilmedi!"); // That means error:no value chosen!
}
}
答案 0 :(得分:0)
您的代码未正确准备path
变量。在一种情况下,它包含文件名,在另一种情况下,它只包含路径名:
if (Form2.dosya_adi != null)
{
string cfile = Form2.chosenfile;
path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase) + "\\DATA\\" + cfile+ ".txt";
}
else
{
path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase)+"\\DATA";
}
然后尝试打开文件 - 即使变量首先不包含文件名。如果这导致异常,则尝试创建文件,但实际上,您并未向路径添加路径分隔符。所以我认为你的catch
块应该是:
StreamWriter Write_File= File.CreateText(path + "\\" + i.ToString() + ".txt");// yeni dosya oluştur.
Write_File.Close();