Dizinin C:/adlandırılmış bir klasör içerip içermediğini nasıl kontrol edebilirim MP_Uploadve yoksa, klasörü otomatik olarak oluşturabilirim?
Visual Studio 2005 C # kullanıyorum.
Yanıtlar:
using System.IO;
...
Directory.CreateDirectory(@"C:\MP_Upload");
Directory.CreateDirectory tam olarak istediğiniz şeyi yapar: Henüz yoksa dizini oluşturur. Önce kesin bir kontrol yapmaya gerek yoktur.
Yolda belirtilen tüm dizinler, halihazırda mevcut olmadıkça veya yolun bir kısmı geçersiz değilse oluşturulur. Path parametresi bir dosya yolunu değil, bir dizin yolunu belirtir. Dizin zaten varsa, bu yöntem hiçbir şey yapmaz.
(Bu ayrıca , yol üzerindeki tüm dizinlerin gerekirse oluşturulduğu anlamına gelir : henüz mevcut olmasa CreateDirectory(@"C:\a\b\c\d")bile yeterlidir C:\a.)
Yine de, dizin seçiminiz hakkında bir uyarı ekleyeyim: Sistem bölümü kökünün hemen altında bir klasör oluşturmak C:\hoş karşılanmaz. Kullanıcının bir klasör seçmesine veya içinde %APPDATA%veya %LOCALAPPDATA%bunun yerine bir klasör oluşturmasına izin vermeyi düşünün (bunun için Environment.GetFolderPath kullanın ). Environment.SpecialFolder numaralandırmasının MSDN sayfası, özel işletim sistemi klasörlerinin ve amaçlarının bir listesini içerir.
EnsureDirectoryExistsyöntemi bulmayı zorlaştırırdı.
Directory.CreateDirectoryklasör adı mevcut bir dosya adıyla eşleşirse atar.
if(!System.IO.Directory.Exists(@"c:\mp_upload"))
{
System.IO.Directory.CreateDirectory(@"c:\mp_upload");
}
Createiçin CreateDirectory:)
using System;
using System.IO;
using System.Windows.Forms;
namespace DirCombination
{
public partial class DirCombination : Form
{
private const string _Path = @"D:/folder1/foler2/folfer3/folder4/file.txt";
private string _finalPath = null;
private string _error = null;
public DirCombination()
{
InitializeComponent();
if (!FSParse(_Path))
Console.WriteLine(_error);
else
Console.WriteLine(_finalPath);
}
private bool FSParse(string path)
{
try
{
string[] Splited = path.Replace(@"//", @"/").Replace(@"\\", @"/").Replace(@"\", "/").Split(':');
string NewPath = Splited[0] + ":";
if (Directory.Exists(NewPath))
{
string[] Paths = Splited[1].Substring(1).Split('/');
for (int i = 0; i < Paths.Length - 1; i++)
{
NewPath += "/";
if (!string.IsNullOrEmpty(Paths[i]))
{
NewPath += Paths[i];
if (!Directory.Exists(NewPath))
Directory.CreateDirectory(NewPath);
}
}
if (!string.IsNullOrEmpty(Paths[Paths.Length - 1]))
{
NewPath += "/" + Paths[Paths.Length - 1];
if (!File.Exists(NewPath))
File.Create(NewPath);
}
_finalPath = NewPath;
return true;
}
else
{
_error = "Drive is not exists!";
return false;
}
}
catch (Exception ex)
{
_error = ex.Message;
return false;
}
}
}
}
String path = Server.MapPath("~/MP_Upload/");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
Bunu deneyebilirsin ..
using System.IO;string path = "C:\MP_Upload";if(!Directory.Exists(path)){
Directory.CreateDirectory(path);}