本文整理汇总了C#中System.IO.DirectoryInfo.GetFiles方法的典型用法代码示例。如果您正苦于以下问题:C# System.IO.DirectoryInfo.GetFiles方法的具体用法?C# System.IO.DirectoryInfo.GetFiles怎么用?C# System.IO.DirectoryInfo.GetFiles使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.IO.DirectoryInfo
的用法示例。
在下文中一共展示了System.IO.DirectoryInfo.GetFiles方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: backup
public static void backup()
{
//verificar se existem mais de 10 backups e deletar os mais antigos
System.IO.DirectoryInfo dirInfo = new System.IO.DirectoryInfo(appDir + "\\backup");
while (dirInfo.GetFiles().Length > 5)
{
System.IO.FileInfo tmp = dirInfo.GetFiles()[0];
foreach (System.IO.FileInfo file in dirInfo.GetFiles())
{
if (tmp.CreationTime < file.CreationTime)
{
tmp = file;
}
}
tmp.Delete();
}
ZipFile zip =
new ZipFile(Library.appDir + "\\backup\\" +
DateTime.Now.Day + DateTime.Now.Month + DateTime.Now.Year +
DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second);
zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression;
zip.AddFile(Library.appDir + "\\db\\cipdatabase.sdf");
zip.Save();
}
示例2: Delete_TempFile
/// <param name="path">删除的文件的路径</param>
/// <param name="date">删除某一个时间点以前的文件</param>
/// <param name="fileType">文件类型</param>
public static void Delete_TempFile(string path,int datePoint,string fileType)
{
System.IO.DirectoryInfo dirInfo = new System.IO.DirectoryInfo(path);
//DateTime time = DateTime.Now.AddDays(-datePoint);
//该目录存在且有临时文件则进行删除处理
if (dirInfo.Exists && dirInfo.GetFiles().Length > 0)
{
System.IO.FileInfo[] files = dirInfo.GetFiles();
for (int i = 0; i < files.Length; i++)
{
if (files[i].Exists)
{
try
{
//将该文件设置为临时文件
System.IO.File.SetAttributes(path + "//" + files[i].Name, System.IO.FileAttributes.Temporary);
//删除指定的文件
System.IO.File.Delete(path + "//" + files[i].Name);
}catch(System.IO.IOException ex)
{
throw ex;
}
}
}
}
}
示例3: xInfoElement
public xInfoElement()
{
g_Singleton = this;
InitializeComponent();
eCArchiveFile E = new eCArchiveFile(FileManager.GetFile("compiled_infos.bin"));
E.Position = 14;
eCDocArchive D = new eCDocArchive(E);
foreach (bCAccessorPropertyObject o in D)
{
InfoWrapper w = new InfoWrapper(o.Class as gCInfo);
m_pData.Add(w.Name.pString, w);
}
System.IO.DirectoryInfo m = new System.IO.DirectoryInfo(FileManager.g_pGamepath + "data\\raw\\infos");
if (m.Exists)
{
foreach (System.IO.FileInfo fi in m.GetFiles("*.xinf"))
{
InfoWrapper w = InfoWrapper.FromXml(System.Xml.Linq.XElement.Load(fi.FullName));
m_pData.Add(w.Name.pString, w);
}
}
listView1.ItemsSource = m_pData.Values;
setElement(m_pData["PANKRATZX2_00647"], 1, 0);
}
示例4: BindData
private void BindData()
{
using(DataTable dt = new DataTable("Files"))
{
dt.Columns.Add("FileID",typeof(long));
dt.Columns.Add("FileName",typeof(string));
dt.Columns.Add("Description",typeof(string));
DataRow dr = dt.NewRow();
dr["FileID"] = 0;
dr["FileName"] = "../spacer.gif"; // use blank.gif for Description Entry
dr["Description"] = "Select Rank Image";
dt.Rows.Add(dr);
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(Request.MapPath(String.Format("{0}images/ranks",Data.ForumRoot)));
System.IO.FileInfo[] files = dir.GetFiles("*.*");
long nFileID = 1;
foreach(System.IO.FileInfo file in files)
{
string sExt = file.Extension.ToLower();
if(sExt!=".gif" && sExt!=".gif" && sExt!=".jpg")
continue;
dr = dt.NewRow();
dr["FileID"] = nFileID++;
dr["FileName"] = file.Name;
dr["Description"] = file.Name;
dt.Rows.Add(dr);
}
RankImage.DataSource = dt;
RankImage.DataValueField = "FileName";
RankImage.DataTextField = "Description";
}
DataBind();
}
示例5: Main
/*
* Arguments:
* First : Path to folder where the files must be renamed
* Second: Search pattern to choose files (ex.: *.hdf5)
* Third : AllDirectories or TopDirectoryOnly
* Fourth: _1 or _2
*/
static void Main(string[] args)
{
bool show_help = true;
if (args.Length == 4)
{
System.IO.DirectoryInfo directory = new System.IO.DirectoryInfo(args[0]);
string new_name;
foreach (System.IO.FileInfo fileToRename in directory.GetFiles(args[1], (System.IO.SearchOption)Enum.Parse(typeof(System.IO.SearchOption), (string)args[2], true)))
{
Console.Write("Cheking file {0}", fileToRename.Name);
if (System.IO.Path.GetFileNameWithoutExtension(fileToRename.Name).EndsWith(args[3]))
{
new_name = fileToRename.FullName.Replace(args[3], "");
System.IO.File.Move(fileToRename.FullName, new_name);
Console.WriteLine("[ OK ]");
}
else
Console.WriteLine("[ SKIPPED ]");
}
show_help = false;
}
if (show_help)
{
Console.WriteLine("Usage: RenameMohidResultsFiles [path] [search_pattern] [recursion] [ends_with]");
Console.WriteLine(" [path] : Path to the folder where the files to rename are.");
Console.WriteLine(" [search_pattern] : Pattern of files to rename. Ex.: *.hdf5");
Console.WriteLine(" [recursion] : AllDirectories to include sub-folders or TopDirectoryOnly");
Console.WriteLine(" [ends_with] : Ending of the name that must \"disappear\"");
Console.WriteLine(" Ex.: _1");
Console.WriteLine(" RunOff_1.hdf5 => RunOff.hdf5");
}
}
示例6: BindData
private void BindData()
{
using ( DataTable dt = new DataTable( "Files" ) )
{
dt.Columns.Add( "FileID", typeof( long ) );
dt.Columns.Add( "FileName", typeof( string ) );
DataRow dr = dt.NewRow();
dr ["FileID"] = 0;
dr ["FileName"] = "Select File (*.pak)";
dt.Rows.Add( dr );
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo( Request.MapPath( String.Format( "{0}images/emoticons", YafForumInfo.ForumFileRoot ) ) );
System.IO.FileInfo [] files = dir.GetFiles( "*.pak" );
long nFileID = 1;
foreach ( System.IO.FileInfo file in files )
{
dr = dt.NewRow();
dr ["FileID"] = nFileID++;
dr ["FileName"] = file.Name;
dt.Rows.Add( dr );
}
File.DataSource = dt;
File.DataValueField = "FileID";
File.DataTextField = "FileName";
}
DataBind();
}
示例7: GetList
public static PrefSound[] GetList(bool allowDefault)
{
List<PrefSound> list = new List<PrefSound>();
if (allowDefault) list.Add(Default);
list.Add(None);
// read available sounds from C:\WINDOWS\Media
string systemPath = Environment.GetFolderPath(Environment.SpecialFolder.System);
string windowsPath = System.IO.Path.GetDirectoryName(systemPath);
string mediaPath = System.IO.Path.Combine(windowsPath, "Media");
if (System.IO.Directory.Exists(mediaPath))
{
System.IO.DirectoryInfo d = new System.IO.DirectoryInfo(mediaPath);
System.IO.FileInfo[] files = d.GetFiles("*.wav");
foreach (System.IO.FileInfo file in files)
{
PrefSound ps = new PrefSound(true, file.Name, file.FullName);
list.Add(ps);
}
}
PrefSound[] arr = list.ToArray();
list.Clear();
list = null;
return arr;
}
示例8: GetHomeSlides
public AjaxControlToolkit.Slide[] GetHomeSlides()
{
string imageFolder = HttpContext.Current.Server.MapPath(@"~/images/PictureGallery/HomePic");
System.IO.DirectoryInfo directory = new System.IO.DirectoryInfo(imageFolder);
AjaxControlToolkit.Slide[] slides = null;
if (directory.Exists)
{
System.IO.FileInfo[] images = directory.GetFiles("*.jpg");
slides = new AjaxControlToolkit.Slide[images.Length];
int i = 0;
foreach (System.IO.FileInfo image in images)
{
string title = image.Name;
string imagePath = "/images/PictureGallery/HomePic/" + title;
slides[i] = new AjaxControlToolkit.Slide(imagePath, title, title);
i++;
}
ShuffleList(slides);
}
return (slides);
}
示例9: XCopy
/// for an example:XCopy("c:\a\", "d:\b\");
/// <summary>Copy source script to report folder</summary>
/// <param name="sourceDir">sourceDir</param>
/// <param name="targetDir">targetDir</param>
public static void XCopy(string sourceDir, string targetDir)
{
//If the source directory exists.
if (System.IO.Directory.Exists(sourceDir))
{
//If the source directory does not exist, create it.
if (!System.IO.Directory.Exists(targetDir))
System.IO.Directory.CreateDirectory(targetDir);
//Get data from sourcedir.
System.IO.DirectoryInfo sourceInfo = new System.IO.DirectoryInfo(sourceDir);
//Copy the files.
System.IO.FileInfo[] files = sourceInfo.GetFiles();
foreach (System.IO.FileInfo file in files)
{
System.IO.File.Copy(sourceDir + "\\" + file.Name, targetDir + "\\" + file.Name, true);
}
//Copy the dir.
System.IO.DirectoryInfo[] dirs = sourceInfo.GetDirectories();
foreach (System.IO.DirectoryInfo dir in dirs)
{
string currentSource = dir.FullName;
string currentTarget = dir.FullName.Replace(sourceDir, targetDir);
System.IO.Directory.CreateDirectory(currentTarget);
//recursion
XCopy(currentSource, currentTarget);
}
}
}
示例10: GetSerialPorts
public static List<string> GetSerialPorts()
{
List<string> result = new List<string>();
try {
System.IO.DirectoryInfo di = new System.IO.DirectoryInfo("/dev");
System.IO.FileInfo[] fi = di.GetFiles("ttyUSB*");
foreach (System.IO.FileInfo f in fi) {
result.Add(f.FullName);
}
} catch (Exception) {
//eh
}
try {
String[] ports = SerialPort.GetPortNames();
foreach (String p in ports) {
result.Add(p);
}
} catch (Exception) {
//eh
}
return result;
}
示例11: GetFiles
public List<FileNames> GetFiles()
{
List<FileNames> listFiles = new List<FileNames>();
System.IO.DirectoryInfo directoryInfo = new System.IO.DirectoryInfo(HostingEnvironment.MapPath("~/App_Data/UploadedFiles"));
int i = 0;
foreach (var item in directoryInfo.GetFiles())
{
FileNames file = new FileNames();
file.FileID = i + 1;
file.FileName = item.Name;
file.FilePath = directoryInfo.FullName + @"\" + item.Name;
string mimeType = "application/unknown";
//string ext = System.IO.Path.GetExtension(item).ToLower();
Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(item.Extension);
//if (regKey != null && regKey.GetValue("Content Type") != null)
mimeType = regKey.GetValue("Content Type").ToString();
//return mimeType;
file.FileContentType = mimeType;
file.FileByte = System.IO.File.ReadAllBytes(file.FilePath);
listFiles.Add(file);
i = i + 1;
}
return listFiles;
}
示例12: Initialize
protected void Initialize()
{
System.IO.DirectoryInfo directoryInfo = new System.IO.DirectoryInfo(source);
System.IO.FileInfo[] filesInfo = directoryInfo.GetFiles();
var files = filesInfo.OrderBy(f => f.FullName);//sort alphabetically
//foreach (System.IO.FileInfo info in filesInfo)
foreach(System.IO.FileInfo info in files)
{
//System.Diagnostics.Debug.WriteLine("Reading " + info.Name + "...");
SvgReader reader = new SvgReader(info.FullName);
//HACK: At this moment only support one Path in a template file. Ideal case is get a group of graphic object.
var elements = reader.GetXMLElements("path");
foreach (XElement element in elements)
{
Path path = new Path();
path.Fill = Brushes.Black;
XAttribute attribute = element.Attribute(XName.Get("d"));
path.Data = (Geometry)new GeometryConverter().ConvertFromString(attribute.Value);//key
//string name = info.Name.ToLower().TrimEnd(new char[] { 'g', 'v', 's', '.' });//caused some ended with 's' interpreted wrongly.
string name = info.Name.ToLower().Substring(0, info.Name.Length - 4);
string label = GetLabel(info.Name);
if (label.Length > 0) name = name.Replace(label, string.Empty);
PathViewModel item = new PathViewModel(name, path, label);
this.items.Add(item);
break;
}
}//end loops
}
示例13: GetLargestFilePathFromDir
public static string GetLargestFilePathFromDir(string startFolder)
{
// Take a snapshot of the file system.
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(startFolder);
// This method assumes that the application has discovery permissions
// for all folders under the specified path.
IEnumerable<System.IO.FileInfo> fileList = dir.GetFiles("*.*", System.IO.SearchOption.AllDirectories);
//Return the size of the largest file
long maxSize =
(from file in fileList
let len = GetFileLength(file)
select len)
.Max();
Console.WriteLine("The length of the largest file under {0} is {1}", startFolder, maxSize);
// Return the FileInfo object for the largest file
// by sorting and selecting from beginning of list
System.IO.FileInfo longestFile =
(from file in fileList
let len = GetFileLength(file)
where len > 0
orderby len descending
select file)
.First();
Console.WriteLine("The largest file under {0} is {1} with a length of {2} bytes",
startFolder, longestFile.FullName, longestFile.Length);
return longestFile.FullName;
}
示例14: GetAllWithServerOptions
/*Server pagination with server option like server filteration and server sorting i.e serverFiltering: true, serverSorting: true,*/
public JsonResult GetAllWithServerOptions(int skip, int take, int page, int pageSize, string group)
{
var sorterCollection = KendoGridSorterCollection.BuildCollection(Request);
var filterCollection = KendoGridFilterCollection.BuildCollection(Request);
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(startFolder);
IEnumerable<System.IO.FileInfo> fileList = dir.GetFiles("*.*", System.IO.SearchOption.AllDirectories);
IEnumerable<System.IO.FileInfo> fulllist = (from file in fileList select file);
/*IEnumerable<System.IO.FileInfo> fullfileinfo =
(from file in fileList select file).Skip(skip).Take(take);*/
var list = fulllist.Select(x => new
{
text = x.Name,
value = x.Name
});
var filteredItems = list.MultipleFilter(filterCollection.Filters);
var sortedItems = filteredItems.MultipleSort(sorterCollection.Sorters).ToList();
var count = sortedItems.Count();
var data = (from v in sortedItems.Skip((page - 1) * pageSize)
.Take(pageSize)
select v).ToList();
return Json(
new
{
File = data,
TotalCount = count
},
JsonRequestBehavior.AllowGet); //alow get while using server grid
}
示例15: Main
// functions
static void Main(string[] args)
{
if (args.Length < 6 )
{
Console.WriteLine("Error -- not enough parameters");
Console.WriteLine("Usage : DataImporter.exe file[path], ip, port, catalog, id, passwd");
Console.ReadKey();
return;
}
DbManager.SetConnString(string.Format("Data Source={0},{1};Initial Catalog={2};USER ID={3};PASSWORD={4}", args[1], args[2], args[3], args[4], args[5]));
// argument가 directory면 파일을 만들고
string listFileName = "";
System.IO.DirectoryInfo dirInfo = new System.IO.DirectoryInfo(args[0]);
if( dirInfo.Exists )
{
listFileName = args[0] + "\\data_table.lst";
System.IO.StreamWriter listWriter = new System.IO.StreamWriter(listFileName);
foreach ( System.IO.FileInfo fileInfo in dirInfo.GetFiles())
{
if(fileInfo.Extension == ".csv" )
{
listWriter.WriteLine(fileInfo.FullName);
}
}
listWriter.Close();
}
else
{
listFileName = args[0];
}
// 시간 측정
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
sw.Reset();
sw.Start();
string[] dataFiles = System.IO.File.ReadAllLines(listFileName, Encoding.Default);
if( dataFiles.Length == 0)
{
Console.WriteLine("Error : invalid file or directory.!");
Console.ReadLine();
return;
}
// 파일이면 해당 파일의 리스트를 읽어서 사용한다.
System.Diagnostics.Process currentProcess = System.Diagnostics.Process.GetCurrentProcess();
FileManager.Init(string.Format("{0}\\{1}.log", System.IO.Directory.GetCurrentDirectory(), currentProcess.ProcessName));
Parallel.For(0, dataFiles.Length, (i) =>
{
FileManager fileManager = new FileManager();
fileManager.ImportToDb(dataFiles[i]);
});
FileManager.Release();
sw.Stop();
Console.WriteLine("수행시간 : {0}", sw.ElapsedMilliseconds / 1000.0f);
Console.ReadLine();
}