2013-05-31 51 views
0

我試圖在我的程序中實現文件命名約定。例如我有一個配置文件,如以下:從配置文件處理文件命名約定

MyConfig.conf 
# File naming convention for output-file 
[Field1][Field3][Field2] 

「FieldX」對應與程序內的字符串 - 因此,例如一個程序將讀取配置文件和格式化字符串作爲在程序如下:

Field1Value Field2Value Field3Value 

有沒有任何首選的方法來做這種事情在C#中?

+0

你的意思是,FieldX可以被配置爲任何字符串?那麼你只需重新排列/格式化FieldX來創建文件名? 還是你的意思是重新配置應該是可配置的? – aiapatag

回答

1

我能想到的最簡單的方法就是使用應用程序設置。應用程序設置包含您需要的字符串格式。然後你只需使用該字符串格式。

using System; 
using System.Collections.Generic; 
using System.Collections.Specialized; 
using System.Configuration; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace _16852548 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      NameValueCollection appSettings = ConfigurationManager.AppSettings; 

      string field1Value = "Filename"; 
      string field2Value = "."; 
      string field3Value = "txt"; 

      string fileFormat = appSettings["FileNameFormat"]; 

      Console.WriteLine(string.Format(fileFormat, field1Value, field2Value, field3Value)); 
     } 
    } 
} 

然後配置文件可以是:

<?xml version="1.0" encoding="utf-8" ?> 
<configuration> 
    <appSettings> 
    <add key="FileNameFormat" value="{0}{2}{1}"/> <!-- follow string.Format syntax --> 
    </appSettings> 
</configuration>