내 응용 프로그램에서 FileUploader 컨트롤을 사용합니다. 지정된 폴더에 파일을 저장하고 싶습니다. 이제이 폴더가 없으면 먼저 폴더를 만들고이 폴더에 파일을 저장하고 싶습니다. 폴더가 이미 있으면 파일을 저장하십시오.
내가 어떻게 할 수 있니?
다른 사람들이 말했듯이, System.IO.Directory.CreateDirectory
그러나 먼저 존재하는지 확인할 필요가 없습니다. docs
경로에 지정된 모든 디렉토리는 이미 존재하지 않거나 경로의 일부가 유효하지 않은 경우 작성됩니다. 디렉토리가 이미 존재하는 경우이 메소드는 새 디렉토리를 작성하지 않지만 기존 디렉토리에 대한 DirectoryInfo 오브젝트를 리턴합니다.
http://forums.asp.net/p/1226236/2209871.aspx :에 따라 아래 코드를 사용하십시오.
string subPath ="ImagesPath"; // your code goes here
bool exists = System.IO.Directory.Exists(Server.MapPath(subPath));
if(!exists)
System.IO.Directory.CreateDirectory(Server.MapPath(subPath));
다음 행을 작성하십시오.
System.IO.Directory.CreateDirectory("my folder");
참조 : MSDN의 Directory.CreateDirectory에 관한 기사
물론 소스 파일의 맨 위에 using System.IO;
를 쓴 다음 폴더를 만들 때마다 Directory.CreateDirectory("my folder");
을 쓸 수도 있습니다.
경로가 아직 존재하지 않으면 다음과 같은 방법으로 경로를 만들 수 있습니다.
using System.IO;
private void CreateIfMissing(string path)
{
bool folderExists = Directory.Exists(Server.MapPath(path));
if (!folderExists)
Directory.CreateDirectory(Server.MapPath(path));
}
Directory.Exists
이것은 FilePath가 있는지 확인하는 방법을 설명합니다
Directory.CreateDirectory
이것은 FilePath가 존재하지 않으면 FilePath를 생성하고 시도하는 방법을 설명합니다
Try/catch 절을 사용하여 존재 여부를 확인할 수 있습니다.
try
{
if (!Directory.Exists(path))
{
// Try to create the directory.
DirectoryInfo di = Directory.CreateDirectory(path);
}
}
catch (IOException ioex)
{
Console.WriteLine(ioex.Message);
}
using System.IO
if (!Directory.Exists(yourDirectory))
Directory.CreateDirectory(yourDirectory);
이 메소드는 존재하지 않으면 폴더를 생성하고 존재하는 경우 아무것도하지 않습니다.
Directory.CreateDirectory(path);
if (!Directory.Exists(Path.GetDirectoryName(fileName)))
{
Directory.CreateDirectory(Path.GetDirectoryName(fileName));
}
다음 코드는 존재하지 않는 경우 디렉토리를 생성하는 데 사용하는 가장 좋은 코드 줄입니다.
System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath("~/temp/"));
디렉토리가 이미 존재하는 경우이 메소드는 새 디렉토리를 작성하지 않지만 기존 디렉토리에 대한 DirectoryInfo 오브젝트를 리턴합니다. >
이것은 내가 찾던 해답 이었지만 쉽게 찾지 못했습니다 :
string pathToNewFolder = System.IO.Path.Combine(parentFolderPath, "NewSubFolder");
DirectoryInfo directory = Directory.CreateDirectory(pathToNewFolder);
// Will create if does not already exist (otherwise will ignore)
아래 코드를 사용하십시오. 이 코드를 파일 복사에 사용하고 새 폴더를 만듭니다.
string fileToCopy = "filelocation\\file_name.txt";
String server = Environment.UserName;
string newLocation = "C:\\Users\\" + server + "\\Pictures\\Tenders\\file_name.txt";
string folderLocation = "C:\\Users\\" + server + "\\Pictures\\Tenders\\";
bool exists = System.IO.Directory.Exists(folderLocation);
if (!exists)
{
System.IO.Directory.CreateDirectory(folderLocation);
if (System.IO.File.Exists(fileToCopy))
{
MessageBox.Show("file copied");
System.IO.File.Copy(fileToCopy, newLocation, true);
}
else
{
MessageBox.Show("no such files");
}
}
string createfolder = "E :/tmp /"+ uId;
System.IO.Directory.CreateDirectory (createfolder);