2012-11-21 2 views
0

app.config에 파일 경로가있는 C# 응용 프로그램을 작성 중이거나 존재하지 않는 경우 덮어 쓸 수 있습니다.아마도 존재하지 않는 경로와 파일에 대해 전체 디렉토리 구조를 만들려면 어떻게해야합니까?

예 : 디렉토리/파일 조합 생성과 <add key="file" value="c:\myapp\file.txt"/>

나는 데 문제.

은 누군가가 나에게 그건 당신이 단지 FileStream을 사용하여 파일을 쓸 수 있습니다 후, 빈 텍스트 파일

답변

3

당신은 아마 폴더를 만들 찾고 포함한 전체 폴더 경로를 만드는 방법의 코드 예제를 제공하시기 바랍니다 수 있습니다.

존재하지 않을 수도있는 디렉토리의 파일에 쓰기 전에 디렉토리를 만드는 편리한 기능이 있습니다.

/// <summary> 
/// Create the folder if not existing for a full file name 
/// </summary> 
/// <param name="filename">full path of the file</param> 
public static void CreateFolderIfNeeded(string filename) { 
    string folder = System.IO.Path.GetDirectoryName(filename); 
    if (!System.IO.Directory.Exists(folder)) { 
    System.IO.Directory.CreateDirectory(folder); 
    } 
} 
0

상세 사항 : 만들 수있는 두 개의 서로 다른 키의 디렉토리 경로 및 파일이 쉽게

의 app.config

<add key="filePath" value="c:\myapp\"/> 
<add key="fileName" value="file.txt"/> 


클래스

string path = ConfigurationManager.AppSettings["filePath"]; 
string fileName = ConfigurationManager.AppSettings["fileName"]; 
string currentPathAndFile = path + fileName; 

if (!File.Exists(currentPathAndFile)) // Does the File and Path exist 
{ 
    if (!Directory.Exists(path)) // Does the directory exist 
     Directory.CreateDirectory(path); 

    // Create a file to write to. 
    using (StreamWriter sw = File.CreateText(currentPathAndFile)) 
    { 
     sw.WriteLine("Hello"); 
     sw.WriteLine("And"); 
     sw.WriteLine("Welcome"); 
    } 
    } 
1

귀하의 질문은 매우 명확하지 않다,하지만 난 당신이

using System.IO; 
... 

string path = ConfigurationManager.AppSettings["FolderPath"]; 
string fullPath = Path.Combine(path, "filename.txt"); 

if(!Directory.Exists(path)) 
{ 
    Directory.CreateDirectory(path); 
} 

using(StreamWriter wr = new StreamWriter(fullPath, FileMode.Create)) 
{ 

} 
같은 것을하고 싶지 같은데
관련 문제