2017-02-23 6 views
1

Windowsフォルダを作成するフォルダの名前はTextBox.Textから取得しますが、このフォルダ内には自動的にapp.configも作成する必要がありますapp.configファイルを使用してフォルダを作成する

は、これは私がこれまでに得たものである:

private void CreateNewCustomer() 
{ 
    Directory.CreateDirectory(@"C:\Users\khaab\Documents\visual studio 2015\Projects\ReadingXML\ReadingXML\bin\Debug\Customers\" + CustomerTextBox.Text); 
    StreamWriter File = new StreamWriter(@"C:\Users\k.abdulrazak\Documents\visual studio 2015\Projects\ReadingXML\ReadingXML\bin\Debug\Customers\app.config"); 
    File.Close(); 
    MessageBox.Show("You have successfully added a customer", "Customer added", MessageBoxButtons.OK); 
} 

はどのように私はそれを行うことができますか?あなたは、例えば、string root = Environment.CurrentDirectoryを新しいフォルダとapp.configファイルを作成するかどうかのルートパスを保持する変数を持っている必要があり

public void SubmitButton_Click(object sender, EventArgs args) 
{ 
    var name = CustomerTextBox.Text 
    if (String.IsNullOrWhiteSpace(name)) 
    { 
      MessageBox.Show("Enter a customer name!"); 
      return; 
    } 
    var result = CreateNewCustomer(name);   

    if (result) 
    { 
     MessageBox.Show("You have successfully added a customer", "Customer added", MessageBoxButtons.OK); 
    } 
    else 
    { 
     MessageBox.Show("Something went wrong.", "Customer add failed", MessageBoxButtons.OK); 
    } 
} 


private bool CreateNewCustomer(string customerName) 
{ 
    var result = true; 

    try 
    { 
     var basepath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Customers"); 
     var custPath = System.IO.Path.Combine(basepath, customerName); 
     var appconfigpath = System.IO.Path.Combine(custPath, "app.config"); 

     if (!System.IO.Directory.Exists(custPath)) 
     { 
      System.IO.Directory.CreateDirectory(custPath); 
     } 
     System.IO.File.Create(appconfigpath); 
    } 
    catch (Exception ex) 
    { 
     System.Diagnostics.Trace.TraceError("Error creating customer folder: {0}", ex); 
     result = false; 
    }  

    return result; 
} 
+0

:次にCreateNewCustomer方法は次のようになります。 .com/en-us/library/d62kzs03(v = vs.110).aspx –

+0

@GlennFerrieご回答いただきありがとうございます。 –

+0

@KhaabはC#のチュートリアルや本を見つける。ファイルの作成は最も基本的なものの1つです。基本を習っていなければ何もできません。ドキュメントのC#プログラミングガイド –

答えて

1

:これはどのように

+0

から[How to:テキストファイルに書き込む](https://msdn.microsoft.com/en-us/library/8bh11f1k.aspx)を確認してください。ありがとうございます! –

0

。 https://msdn.microsoft:MSDNリンク - 代わりに `StreamWriter`の`私はあなたが `System.IO.File.Create(文字列)を使用しようとすべきだと思う

public void CreateNewCustomer() 
{ 
    var di = Directory.CreateDirectory(Path.Combine(root, CustomerTextBox.Text)); 
    if (di.Exists) 
    { 
     var fs = File.Create(Path.Combine(di.FullName, "app.config")); 
     fs.Close(); 
     MessageBox.Show("You have successfully added a customer", "Customer added", MessageBoxButtons.OK); 
    }  
} 
関連する問題