Here are the examples of the csharp api System.IO.DirectoryInfo.CreateSubdirectory(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
164 Examples
19
Source : FileHelper.cs
with GNU General Public License v3.0
from 9vult
with GNU General Public License v3.0
from 9vult
public static DirectoryInfo CreateFolder(DirectoryInfo parent, string name)
{
return parent.CreateSubdirectory(name);
}
19
Source : ClonesManager.cs
with MIT License
from adrenak
with MIT License
from adrenak
private static void CopyDirectoryWithProgressBarRecursive(DirectoryInfo source, DirectoryInfo destination,
ref long totalBytes, ref long copiedBytes, string progressBarPrefix = "")
{
/// Directory cannot be copied into itself.
if (source.FullName.ToLower() == destination.FullName.ToLower())
{
Debug.LogError("Cannot copy directory into itself.");
return;
}
/// Calculate total bytes, if required.
if (totalBytes == 0)
{
totalBytes = ClonesManager.GetDirectorySize(source, true, progressBarPrefix);
}
/// Create destination directory, if required.
if (!Directory.Exists(destination.FullName))
{
Directory.CreateDirectory(destination.FullName);
}
/// Copy all files from the source.
foreach (FileInfo file in source.GetFiles())
{
try
{
file.CopyTo(Path.Combine(destination.ToString(), file.Name), true);
}
catch (IOException)
{
/// Some files may throw IOException if they are currently open in Unity editor.
/// Just ignore them in such case.
}
/// Account the copied file size.
copiedBytes += file.Length;
/// Display the progress bar.
float progress = (float)copiedBytes / (float)totalBytes;
bool cancelCopy = EditorUtility.DisplayCancelableProgressBar(
progressBarPrefix + "Copying '" + source.FullName + "' to '" + destination.FullName + "'...",
"(" + (progress * 100f).ToString("F2") + "%) Copying file '" + file.Name + "'...",
progress);
if (cancelCopy) return;
}
/// Copy all nested directories from the source.
foreach (DirectoryInfo sourceNestedDir in source.GetDirectories())
{
DirectoryInfo nextDestingationNestedDir = destination.CreateSubdirectory(sourceNestedDir.Name);
ClonesManager.CopyDirectoryWithProgressBarRecursive(sourceNestedDir, nextDestingationNestedDir,
ref totalBytes, ref copiedBytes, progressBarPrefix);
}
}
19
Source : GitRepository.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn
with BSD 3-Clause "New" or "Revised" License
from Altinn
private static void CopyAll(string sourceDirectory, string targetDirectory)
{
DirectoryInfo source = new DirectoryInfo(sourceDirectory);
DirectoryInfo target = new DirectoryInfo(targetDirectory);
foreach (FileInfo file in source.GetFiles())
{
File.SetAttributes(file.FullName, FileAttributes.Normal);
file.CopyTo(Path.Combine(target.FullName, file.Name), true);
}
foreach (DirectoryInfo subDirectiory in source.GetDirectories())
{
DirectoryInfo nextTargetSubDir =
target.CreateSubdirectory(subDirectiory.Name);
CopyAll(subDirectiory.FullName, nextTargetSubDir.FullName);
}
}
19
Source : SvnSccContext.cs
with Apache License 2.0
from AmpScm
with Apache License 2.0
from AmpScm
private void RecursiveCopy(DirectoryInfo source, DirectoryInfo destination)
{
foreach (FileInfo sourceFile in source.GetFiles())
{
FileInfo destFile = sourceFile.CopyTo(Path.Combine(destination.FullName, sourceFile.Name));
destFile.Attributes = sourceFile.Attributes;
}
foreach (DirectoryInfo subDirSource in source.GetDirectories())
{
DirectoryInfo subDirDestination = destination.CreateSubdirectory(subDirSource.Name);
subDirDestination.Attributes = subDirSource.Attributes;
RecursiveCopy(subDirSource, subDirDestination);
}
}
19
Source : FileManager.cs
with MIT License
from angelsix
with MIT License
from angelsix
private static void CopyFolderRecursive(DirectoryInfo source, DirectoryInfo target)
{
// Make sure destination folder exists
Directory.CreateDirectory(target.FullName);
// Get each file in the folder...
foreach (var file in source.GetFiles())
// And copy it to the destination
file.CopyTo(Path.Combine(target.FullName, file.Name), true);
// Get each sub-folder...
foreach (var subFolder in source.GetDirectories())
// Recursively copy
CopyFolderRecursive(subFolder, target.CreateSubdirectory(subFolder.Name));
}
19
Source : util.cs
with GNU Lesser General Public License v3.0
from angturil
with GNU Lesser General Public License v3.0
from angturil
public static void CopyFilesRecursively(DirectoryInfo source, DirectoryInfo target)
{
foreach (DirectoryInfo dir in source.GetDirectories())
{
CopyFilesRecursively(dir, target.CreateSubdirectory(dir.Name));
}
foreach (FileInfo file in source.GetFiles())
{
string newFilePath = Path.Combine(target.FullName, file.Name);
try
{
file.CopyTo(newFilePath);
}
catch (Exception)
{
}
}
}
19
Source : CopyDir.cs
with MIT License
from Astropilot
with MIT License
from Astropilot
public static void CopyAll(DirectoryInfo source, DirectoryInfo target)
{
if (source.FullName.ToLower() == target.FullName.ToLower())
{
return;
}
// Check if the target directory exists, if not, create it.
if (Directory.Exists(target.FullName) == false)
{
Directory.CreateDirectory(target.FullName);
}
// Copy each file into it's new directory.
foreach (FileInfo fi in source.GetFiles())
{
Console.WriteLine(@"Copying {0}\{1}", target.FullName, fi.Name);
fi.CopyTo(Path.Combine(target.ToString(), fi.Name), true);
}
// Copy each subdirectory using recursion.
foreach (DirectoryInfo diSourceSubDir in source.GetDirectories())
{
DirectoryInfo nextTargetSubDir =
target.CreateSubdirectory(diSourceSubDir.Name);
CopyAll(diSourceSubDir, nextTargetSubDir);
}
}
19
Source : UnitTest1.cs
with GNU General Public License v3.0
from autodotua
with GNU General Public License v3.0
from autodotua
private void CreateFiles()
{
if (Directory.Exists("test"))
{
Directory.Delete("test", true);
}
var root = Directory.CreateDirectory("test");
var dir1 = root.CreateSubdirectory("dir1");
IOFile.WriteAllText(Path.Combine(dir1.FullName, "����-1.mp4"), "");
IOFile.WriteAllText(Path.Combine(dir1.FullName, "����-2.mp4"), "");
IOFile.WriteAllText(Path.Combine(dir1.FullName, "����-1.mp4"), "");
IOFile.WriteAllText(Path.Combine(dir1.FullName, "����-2.mp4"), "");
var dir2 = dir1.CreateSubdirectory("dir2");
IOFile.WriteAllText(Path.Combine(dir2.FullName, "�ɻ�-1.mp4"), "");
IOFile.WriteAllText(Path.Combine(dir2.FullName, "����-2.txt"), "");
var dir3 = root.CreateSubdirectory("����");
IOFile.WriteAllText(Path.Combine(dir3.FullName, "1.mp4"), "");
IOFile.WriteAllText(Path.Combine(dir3.FullName, "2.mp4"), "");
IOFile.WriteAllText(Path.Combine(dir3.FullName, "1.jpg"), "");
IOFile.WriteAllText(Path.Combine(dir3.FullName, "2.jpg"), "");
var dir4 = root.CreateSubdirectory("����");
IOFile.WriteAllText(Path.Combine(dir4.FullName, "1.mp4"), "");
IOFile.WriteAllText(Path.Combine(dir4.FullName, "2.jpg"), "");
IOFile.WriteAllText(Path.Combine(dir4.FullName, "3.jpg"), "");
IOFile.WriteAllText(Path.Combine(dir4.FullName, "4.mp4"), "");
}
19
Source : OutputFilesService.cs
with Apache License 2.0
from AutomateThePlanet
with Apache License 2.0
from AutomateThePlanet
private void CopyAll(DirectoryInfo source, DirectoryInfo target)
{
Directory.CreateDirectory(target.FullName);
// Copy each file into the new directory.
foreach (var fileInfo in source.GetFiles())
{
fileInfo.CopyTo(Path.Combine(target.FullName, fileInfo.Name), true);
}
// Copy each subdirectory using recursion.
foreach (var dirInfoSourceSubDir in source.GetDirectories())
{
var nextTargetSubDir =
target.CreateSubdirectory(dirInfoSourceSubDir.Name);
CopyAll(dirInfoSourceSubDir, nextTargetSubDir);
}
}
19
Source : NativeTestsRunnerPluginService.cs
with Apache License 2.0
from AutomateThePlanet
with Apache License 2.0
from AutomateThePlanet
private void CopyAll(DirectoryInfo source, DirectoryInfo target)
{
Directory.CreateDirectory(target.FullName);
// Copy each file into the new directory.
foreach (FileInfo fi in source.GetFiles())
{
Console.WriteLine(@"Copying {0}\{1}", target.FullName, fi.Name);
fi.CopyTo(Path.Combine(target.FullName, fi.Name), true);
}
// Copy each subdirectory using recursion.
foreach (DirectoryInfo diSourceSubDir in source.GetDirectories())
{
DirectoryInfo nextTargetSubDir = target.CreateSubdirectory(diSourceSubDir.Name);
CopyAll(diSourceSubDir, nextTargetSubDir);
}
}
19
Source : ModifyUnityAndroidAppManifestSample.cs
with GNU General Public License v3.0
from berichan
with GNU General Public License v3.0
from berichan
public static void CopyAll(DirectoryInfo source, DirectoryInfo target)
{
Directory.CreateDirectory(target.FullName);
// Copy each file into the new directory.
foreach (FileInfo fi in source.GetFiles())
{
if (fi.Name.EndsWith("meta"))
continue;
Debug.Log($"Copying " + target.FullName +" to " + fi.Name);
fi.CopyTo(Path.Combine(target.FullName, fi.Name), true);
}
// Copy each subdirectory using recursion.
foreach (DirectoryInfo diSourceSubDir in source.GetDirectories())
{
DirectoryInfo nextTargetSubDir =
target.CreateSubdirectory(diSourceSubDir.Name);
CopyAll(diSourceSubDir, nextTargetSubDir);
}
}
19
Source : SettingsFileHelper.cs
with MIT License
from Berrysoft
with MIT License
from Berrysoft
private static void CreateSettingsFolder(string projName)
{
DirectoryInfo home = new DirectoryInfo(appDataPath);
home.CreateSubdirectory(projName);
}
19
Source : DirectoryEx.cs
with MIT License
from BluePointLilac
with MIT License
from BluePointLilac
public static void CopyTo(string srcDirPath, string dstDirPath)
{
DirectoryInfo srcDi = new DirectoryInfo(srcDirPath);
DirectoryInfo dstDi = new DirectoryInfo(dstDirPath);
dstDi.Create();
foreach(FileInfo srcFi in srcDi.GetFiles())
{
string dstFilePath = $@"{dstDirPath}\{srcFi.Name}";
srcFi.CopyTo(dstFilePath, true);
}
foreach(DirectoryInfo srcSubDi in srcDi.GetDirectories())
{
DirectoryInfo dstSubDi = dstDi.CreateSubdirectory(srcSubDi.Name);
CopyTo(srcSubDi.FullName, dstSubDi.FullName);
}
}
19
Source : PackageConfigurationUpdater.cs
with MIT License
from bonsai-rx
with MIT License
from bonsai-rx
static void CopyDirectory(DirectoryInfo source, DirectoryInfo target)
{
if (source.FullName.Equals(target.FullName, StringComparison.OrdinalIgnoreCase)) return;
if (!target.Exists) Directory.CreateDirectory(target.FullName);
foreach (var file in source.GetFiles())
{
file.CopyTo(Path.Combine(target.FullName, file.Name), true);
}
foreach (var directory in source.GetDirectories())
{
var targetDirectory = target.CreateSubdirectory(directory.Name);
CopyDirectory(directory, targetDirectory);
}
}
19
Source : IoHelpers.cs
with GNU General Public License v3.0
from chaincase-app
with GNU General Public License v3.0
from chaincase-app
public static void CopyFilesRecursively(DirectoryInfo source, DirectoryInfo target)
{
foreach (DirectoryInfo dir in source.GetDirectories())
{
CopyFilesRecursively(dir, target.CreateSubdirectory(dir.Name));
}
foreach (FileInfo file in source.GetFiles())
{
file.CopyTo(Path.Combine(target.FullName, file.Name));
}
}
19
Source : TxFileManager.cs
with MIT License
from chinhdo
with MIT License
from chinhdo
public static void CopyAll(DirectoryInfo source, DirectoryInfo target)
{
if (source is null)
{
throw new ArgumentNullException(nameof(source));
}
if (target is null)
{
throw new ArgumentNullException(nameof(target));
}
Directory.CreateDirectory(target.FullName);
// Copy each file into the new directory.
foreach (FileInfo fi in source.GetFiles())
{
fi.CopyTo(Path.Combine(target.FullName, fi.Name), true);
}
// Copy each subdirectory using recursion.
foreach (DirectoryInfo diSourceSubDir in source.GetDirectories())
{
DirectoryInfo nextTargetSubDir = target.CreateSubdirectory(diSourceSubDir.Name);
CopyAll(diSourceSubDir, nextTargetSubDir);
}
}
19
Source : BI_DIR.cs
with MIT License
from ChrisStayte
with MIT License
from ChrisStayte
public void CopyAll(DirectoryInfo source, DirectoryInfo target)
{
Directory.CreateDirectory(target.FullName);
// Copy each file into the new directory.
foreach (FileInfo fi in source.GetFiles())
{
Console.WriteLine(@"Copying {0}\{1}", target.FullName, fi.Name);
fi.CopyTo(Path.Combine(target.FullName, fi.Name), true);
}
// Copy each subdirectory using recursion.
foreach (DirectoryInfo diSourceSubDir in source.GetDirectories())
{
DirectoryInfo nextTargetSubDir =
target.CreateSubdirectory(diSourceSubDir.Name);
CopyAll(diSourceSubDir, nextTargetSubDir);
}
}
19
Source : ConverterUtils.cs
with MIT License
from colinator27
with MIT License
from colinator27
public static void CopyDataFiles(ProjectFile pf)
{
if (pf.JsonFile.DataFiles != null && pf.JsonFile.DataFiles.Trim() != "")
{
string dataFileDir = Path.Combine(pf.DirectoryPath, pf.JsonFile.DataFiles);
if (Directory.Exists(dataFileDir))
{
void CopyFiles(DirectoryInfo source, DirectoryInfo target)
{
foreach (DirectoryInfo subDir in source.GetDirectories())
CopyFiles(subDir, target.CreateSubdirectory(subDir.Name));
foreach (FileInfo file in source.GetFiles())
{
pf.DataHandle.Logger?.Invoke($"Writing data file \"{file.Name}\"...");
file.CopyTo(Path.Combine(target.FullName, file.Name), true);
}
}
CopyFiles(new DirectoryInfo(dataFileDir), new DirectoryInfo(pf.DataHandle.Directory));
}
}
}
19
Source : System_IO_DirectoryInfo_Binding.cs
with MIT License
from CragonGame
with MIT License
from CragonGame
static StackObject* CreateSubdirectory_5(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 2);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.String @path = (System.String)typeof(System.String).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
System.IO.DirectoryInfo instance_of_this_method = (System.IO.DirectoryInfo)typeof(System.IO.DirectoryInfo).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
var result_of_this_method = instance_of_this_method.CreateSubdirectory(@path);
return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method);
}
19
Source : Helpers.cs
with GNU General Public License v3.0
from cryptoprofitswitcher
with GNU General Public License v3.0
from cryptoprofitswitcher
internal static string GetJsonFromUrl(string url, bool enableCaching, DirectoryInfo appRootFolder, CancellationToken ct)
{
DirectoryInfo cacheFolder = null;
if (appRootFolder != null)
{
cacheFolder = appRootFolder.CreateSubdirectory("Cache");
}
string responseBody;
try
{
using var client = new HttpClient(new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate });
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.UserAgent.TryParseAdd("request");
HttpResponseMessage response = client.GetAsync(new Uri(url), ct).Result;
response.EnsureSuccessStatusCode();
using HttpContent content = response.Content;
responseBody = response.Content.ReadreplacedtringAsync().Result;
//Save to cache
if (enableCaching && !url.Contains("127.0.0.1", StringComparison.InvariantCulture))
{
int tries = 0;
while (tries < 2)
{
tries++;
try
{
string hashedFilename = CreateMd5(url) + ".json";
if (cacheFolder != null)
{
string savePath = Path.Combine(cacheFolder.FullName, hashedFilename);
_lock.EnterWriteLock();
File.WriteAllText(savePath, responseBody);
}
_lock.ExitWriteLock();
}
catch (Exception ex)
{
Log.Debug("Couldn't save to cache: " + ex);
// Reset Cache
_lock.EnterWriteLock();
cacheFolder?.Delete();
_lock.ExitWriteLock();
}
}
}
return responseBody;
}
catch (Exception ex)
{
Log.Debug("Couldn't get data from: " + url);
Log.Debug("Error message: " + ex.Message);
//Try to get from cache
if (cacheFolder != null)
{
string hashedFilename = CreateMd5(url) + ".json";
var cachedFile = cacheFolder.GetFiles(hashedFilename).First();
var cachedContent = File.ReadAllText(cachedFile.FullName);
Console.WriteLine("Got data from cache.");
return cachedContent;
}
throw;
}
}
19
Source : Program.cs
with GNU General Public License v3.0
from cryptoprofitswitcher
with GNU General Public License v3.0
from cryptoprofitswitcher
private static void DownloadMiners()
{
try
{
if (!Config.DisableDownloadMiners)
{
var minersFolder = AppFolder.CreateSubdirectory("Miners");
if (!minersFolder.EnumerateFiles().Any())
{
WriteInfo(" Downloading miners..");
if (Helpers.IsWindows())
{
DownloadAndExtractFromGithub("https://api.github.com/repos/todxx/teamredminer/releases/latest", "win", "teamredminer", minersFolder);
DownloadAndExtractFromGithub("https://api.github.com/repos/xmrig/xmrig/releases/latest", "gcc-win64", "xmrig", minersFolder);
}
if (Helpers.IsLinux())
{
DownloadAndExtractFromGithub("https://api.github.com/repos/todxx/teamredminer/releases/latest", "linux", "teamredminer", minersFolder);
DownloadAndExtractFromGithub("https://api.github.com/repos/xmrig/xmrig/releases/latest", "xenial-x64", "xmrig", minersFolder);
}
}
}
}
catch (Exception e)
{
Log.Warning(e, "Downloading miners failed.");
}
}
19
Source : FileTests.cs
with Apache License 2.0
from cs-util-com
with Apache License 2.0
from cs-util-com
private static void TesreplacederationInFolder(DirectoryInfo rootDir) {
rootDir.CreateSubdirectory("Dir1");
rootDir.GetChildDir("Dir2").CreateV2();
replacedert.True(rootDir.GetChildDir("Dir1").ExistsV2());
replacedert.True(rootDir.GetChildDir("Dir2").IsNotNullAndExists());
SaveAndLoadTextToFile(rootDir.GetChild("File1.txt"), textToSave: "Test 123");
replacedert.True(rootDir.GetChild("File1.txt").ExistsV2());
replacedert.True(rootDir.GetChild("File1.txt").IsNotNullAndExists());
replacedert.Equal(2, rootDir.GetDirectories().Count());
replacedert.Single(rootDir.GetFiles());
replacedert.Equal(2, rootDir.EnumerateDirectories().Count());
replacedert.Single(rootDir.EnumerateFiles());
replacedert.Equal(3, rootDir.EnumerateFileSystemInfos().Count());
}
19
Source : FileTests.cs
with Apache License 2.0
from cs-util-com
with Apache License 2.0
from cs-util-com
[Fact]
public void TestFileRenameAndMove() {
var rootDir = CreateDirectoryForTesting("TestFileRenameAndMove");
var myFile = rootDir.GetChild("MyFile1.txt");
SaveAndLoadTextToFile(myFile, textToSave: "Test 123");
replacedert.True(myFile.IsNotNullAndExists());
var newName = "MyFile2.txt";
var oldPath = new FileInfo(myFile.FullPath());
myFile.Rename(newName);
replacedert.Equal(oldPath.ParentDir().FullPath(), myFile.ParentDir().FullPath());
replacedert.Equal(newName, myFile.Name);
replacedert.NotEqual(oldPath.Name, myFile.Name);
var subdir = rootDir.CreateSubdirectory("subdir");
myFile.MoveToV2(subdir);
replacedert.Single(subdir.GetFiles()); // The folder should now contain 1 entry
replacedert.Equal(subdir.FullPath(), myFile.ParentDir().FullPath());
rootDir.DeleteV2();
}
19
Source : ConfigForm.cs
with BSD 2-Clause "Simplified" License
from David-JonesDVN
with BSD 2-Clause "Simplified" License
from David-JonesDVN
public void Refreshcrap()
{
crapCfg.Items.Clear();
crapCfg.Items.Add("None");
crapGame.Items.Clear();
crapGame.Items.Add("None");
if (MainForm.curCfg.crapDir != "")
{
if (File.Exists(MainForm.curCfg.crapDir + "\\config\\games.js"))
{
crap = JsonConvert.DeserializeObject<Dictionary<string, string>>(File.ReadAllText(MainForm.curCfg.crapDir + "\\config\\games.js"));
foreach (KeyValuePair<string, string> line in crap)
{
int number = Int32.TryParse(new String(line.Key.Where(Char.IsDigit).ToArray()), out number) ? number : 0;
if (number == MainForm.idToNumber[game] || !line.Key.StartsWith("th"))
{
crapGame.Items.Add(line.Key);
}
}
}
foreach (FileInfo file in new DirectoryInfo(MainForm.curCfg.crapDir).CreateSubdirectory("config").GetFiles("*.js").Where(n => n.Name != "games.js" && n.Name != "config.js"))
{
crapCfg.Items.Add(file.Name);
}
}
if (MainForm.curCfg.crapDir != "")
crapCfg.Items.Add("Custom");
crapGame.SelectedIndexChanged -= crapCfg_SelectedIndexChanged;
crapCfg.SelectedIndexChanged -= crapCfg_SelectedIndexChanged;
crapGame.SelectedItem = MainForm.curCfg.gameCFG[game].crapCFG[0];
crapCfg.SelectedItem = MainForm.curCfg.gameCFG[game].crapCFG[1];
crapGame.SelectedIndexChanged += crapCfg_SelectedIndexChanged;
crapCfg.SelectedIndexChanged += crapCfg_SelectedIndexChanged;
}
19
Source : thcrap.cs
with BSD 2-Clause "Simplified" License
from David-JonesDVN
with BSD 2-Clause "Simplified" License
from David-JonesDVN
private void thcrap_Load(object sender, EventArgs e)
{
repoList.Items.Add(MainForm.rm.GetString("selectedPatches"));
if (File.Exists(gamejs))
{
profileData profile = JsonConvert.DeserializeObject<profileData>(File.ReadAllText(gamejs));
foreach (Dictionary<string, string> patch in profile.patches)
{
if (!patchStates.Contains(patch["archive"]))
patchStates.Add(patch["archive"].Substring(6));
}
}
foreach (FileInfo localRepo in new DirectoryInfo(MainForm.curCfg.crapDir).CreateSubdirectory("repos").GetFiles("repo.js", SearchOption.AllDirectories))
{
addRepo(File.ReadAllText(localRepo.FullName), true);
}
searchRepo(MainForm.curCfg.StartingRepo);
if (File.Exists(MainForm.curCfg.crapDir + "\\config\\games.js"))
games = JsonConvert.DeserializeObject<Dictionary<string, string>>(File.ReadAllText(MainForm.curCfg.crapDir + "\\config\\games.js"));
for (int i = 0; i < 3; i += 2)
{
if (MainForm.curCfg.gameCFG[cfgForm.game].GameDir[i] != "" && !games.ContainsValue(MainForm.curCfg.gameCFG[cfgForm.game].GameDir[i].Replace("\\", "/")))
{
string augment = i == 2 ? "_custom" : "";
games.Add("th" + (MainForm.idToNumber[cfgForm.game]).ToString("00") + augment, MainForm.curCfg.gameCFG[cfgForm.game].GameDir[i].Replace("\\", "/"));
}
}
RefreshProfiles();
}
19
Source : DeleteFolderAction.cs
with MIT License
from DCourtel
with MIT License
from DCourtel
[TestMethod]
public void DeleteTheFolder_WhenItContainsFilesAndSubFolders()
{
// Arrange
SUT action = new SUT(Tools.GetXmlFragment("DeleteFolderAction.CustAct"));
DirectoryInfo folderToDelete = new DirectoryInfo(action.FolderPath);
var finalResult = Tools.GetReturnCodeAction();
// Act
if (folderToDelete.Exists)
{
folderToDelete.Delete(true);
folderToDelete.Refresh();
replacedert.IsFalse(folderToDelete.Exists);
}
folderToDelete.Create();
folderToDelete.Refresh();
replacedert.IsTrue(folderToDelete.Exists);
folderToDelete.CreateSubdirectory(@"SecondLevel\ThirdLevel");
folderToDelete.CreateSubdirectory("Another Folder");
StreamWriter writer = new StreamWriter(Path.Combine(folderToDelete.FullName, "test1.txt"));
writer.Write("test");
writer.Close();
writer = new StreamWriter(Path.Combine(folderToDelete.FullName, "test2.txt"));
writer.Write("test");
writer.Close();
action.Run(ref finalResult);
folderToDelete.Refresh();
// replacedert
replacedert.IsFalse(folderToDelete.Exists);
}
19
Source : ServerTester.cs
with MIT License
from dgarage
with MIT License
from dgarage
static void CopyAll(DirectoryInfo source, DirectoryInfo target)
{
Directory.CreateDirectory(target.FullName);
// Copy each file into the new directory.
foreach (FileInfo fi in source.GetFiles())
{
fi.CopyTo(Path.Combine(target.FullName, fi.Name), true);
}
// Copy each subdirectory using recursion.
foreach (DirectoryInfo diSourceSubDir in source.GetDirectories())
{
DirectoryInfo nextTargetSubDir =
target.CreateSubdirectory(diSourceSubDir.Name);
CopyAll(diSourceSubDir, nextTargetSubDir);
}
}
19
Source : Program.cs
with MIT License
from diamondo25
with MIT License
from diamondo25
private static void ExtractFile(NameSpaceFile nsf, DirectoryInfo currentOutputDirectory)
{
var path = Path.Combine(currentOutputDirectory.FullName, nsf.Name);
bool useJson = !exportBson;
var obj = nsf.Object as WzProperty;
if (obj == null)
{
Console.WriteLine("Unable to export {0}, as its not a WzProperty", nsf.NodePath);
return;
}
byte[] data;
using (var exp = new Exporter(exportOptions, obj))
{
if (useJson) data = Encoding.ASCII.GetBytes(exp.ToJson());
else data = exp.ToBson();
if (exportOptions.HasFlag(Options.ExternalImageExport))
{
// Generate image path of the first 4 characters of the name (if possible)
var imgDir = globalOutputDirectory.CreateSubdirectory("images");
var name = obj.Name.Replace(".img", "");
if (name.Length > 0) imgDir = imgDir.CreateSubdirectory("" + name[0]);
if (name.Length > 1) imgDir = imgDir.CreateSubdirectory("" + name[1]);
if (name.Length > 2) imgDir = imgDir.CreateSubdirectory("" + name[2]);
if (name.Length > 3) imgDir = imgDir.CreateSubdirectory("" + name[3]);
ExtractImages(exp, imgDir);
}
}
nsf.Checksum = (int)Crc32Algorithm.Compute(data);
// This will replace .img with .hash.(json|bson)
var outputFile = Path.ChangeExtension(path, $".{nsf.Checksum:X8}." + (useJson ? "json" : "bson"));
if (File.Exists(outputFile)) return;
Console.WriteLine("Writing {0}", outputFile);
File.WriteAllBytes(
outputFile,
data
);
}
19
Source : State.cs
with Microsoft Public License
from Dijji
with Microsoft Public License
from Dijji
private DirectoryInfo ObtainDataDirectory()
{
DirectoryInfo di = new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));
DirectoryInfo target = di.GetDirectories().Where(d => d.Name == "FileMeta").FirstOrDefault();
if (target == null)
target = di.CreateSubdirectory("FileMeta");
return target;
}
19
Source : DirectoryHelper.cs
with MIT License
from dogged
with MIT License
from dogged
public static void CopyFilesRecursively(DirectoryInfo source, DirectoryInfo target)
{
foreach (DirectoryInfo dir in source.GetDirectories())
{
CopyFilesRecursively(dir, target.CreateSubdirectory(Rename(dir.Name)));
}
foreach (FileInfo file in source.GetFiles())
{
file.CopyTo(Path.Combine(target.FullName, Rename(file.Name)));
}
}
19
Source : Utility.IO.cs
with MIT License
from DonnYep
with MIT License
from DonnYep
public static void CopyAll(DirectoryInfo source, DirectoryInfo target)
{
Directory.CreateDirectory(target.FullName);
//复制所有文件到新地址
foreach (FileInfo fi in source.GetFiles())
{
fi.CopyTo(Path.Combine(target.FullName, fi.Name), true);
}
//递归拷贝所有子目录
foreach (DirectoryInfo diSourceSubDir in source.GetDirectories())
{
DirectoryInfo nextTargetSubDir =
target.CreateSubdirectory(diSourceSubDir.Name);
CopyAll(diSourceSubDir, nextTargetSubDir);
}
}
19
Source : DirectorySvgConverter.cs
with MIT License
from dotnet-campus
with MIT License
from dotnet-campus
private void ProcessConversion(DirectoryInfo source, DirectoryInfo target)
{
// Convert the files in the specified directory...
this.ConvertFiles(source, target);
if (!_isRecursive)
{
return;
}
// If recursive, process any sub-directory...
DirectoryInfo[] arrSourceInfo = source.GetDirectories();
int dirCount = (arrSourceInfo == null) ? 0 : arrSourceInfo.Length;
for (int i = 0; i < dirCount; i++)
{
DirectoryInfo sourceInfo = arrSourceInfo[i];
FileAttributes fileAttr = sourceInfo.Attributes;
if (!_includeHidden)
{
if ((fileAttr & FileAttributes.Hidden) == FileAttributes.Hidden)
{
continue;
}
}
DirectoryInfo targetInfo = null;
// 不适用的代码
//if (_includeSecurity)
//{
// targetInfo = target.CreateSubdirectory(sourceInfo.Name,
// sourceInfo.GetAccessControl());
//}
//else
//{
targetInfo = target.CreateSubdirectory(sourceInfo.Name);
//}
targetInfo.Attributes = fileAttr;
this.ProcessConversion(sourceInfo, targetInfo);
}
}
19
Source : DirectoryCopier.cs
with MIT License
from dotnet-campus
with MIT License
from dotnet-campus
private void Copy(DirectoryInfo source, DirectoryInfo target)
{
CopyFiles(source, target);
if (!_isRecursive)
{
return;
}
DirectoryInfo[] arrSourceInfo = source.GetDirectories();
int dirCount = (arrSourceInfo == null) ? 0 : arrSourceInfo.Length;
for (int i = 0; i < dirCount; i++)
{
DirectoryInfo sourceInfo = arrSourceInfo[i];
FileAttributes fileAttr = sourceInfo.Attributes;
if (!_includeHidden)
{
if ((fileAttr & FileAttributes.Hidden) == FileAttributes.Hidden)
{
continue;
}
}
DirectoryInfo targetInfo = null;
// 不适用的代码
//if (_includeSecurity)
//{
// targetInfo = target.CreateSubdirectory(sourceInfo.Name,
// sourceInfo.GetAccessControl());
//}
//else
//{
targetInfo = target.CreateSubdirectory(sourceInfo.Name);
//}
targetInfo.Attributes = fileAttr;
Copy(sourceInfo, targetInfo);
}
}
19
Source : Hooks.cs
with GNU Lesser General Public License v3.0
from DynamicHands
with GNU Lesser General Public License v3.0
from DynamicHands
private void TakeScreenshot(IWebDriver driver)
{
try
{
string fileNameBase = string.Format("error_{0}_{1}_{2}",
_featureContext.FeatureInfo.replacedle,
_scenarioContext.ScenarioInfo.replacedle,
DateTime.Now.ToString("yyyyMMdd_HHmmss"))
.Replace(' ', '_')
.Replace(":", "");
var directory = new DirectoryInfo(Directory.GetCurrentDirectory());
if (!directory.Name.Equals("TestResults", StringComparison.InvariantCultureIgnoreCase))
{
directory = directory.CreateSubdirectory("TestResults");
}
Logger.WriteLine($"Screenshot path: {directory.FullName}");
string pageSource = driver.PageSource;
string sourceFilePath = Path.Combine(directory.FullName, fileNameBase + "_source.html");
File.WriteAllText(sourceFilePath, pageSource, Encoding.UTF8);
Console.WriteLine("Page source: {0}", new Uri(sourceFilePath));
if (driver is ITakesScreenshot takesScreenshot)
{
var screenshot = takesScreenshot.GetScreenshot();
string screenshotFilePath = Path.Combine(directory.FullName, fileNameBase + "_screenshot.png");
screenshot.SaveAsFile(screenshotFilePath, ScreenshotImageFormat.Png);
Logger.WriteLine($"Screenshot: {new Uri(screenshotFilePath)}");
}
}
catch (Exception ex)
{
Logger.WriteLine($"Error while taking screenshot: {ex}");
}
}
19
Source : AppBundler.cs
with MIT License
from egramtel
with MIT License
from egramtel
private void CopyFiles(DirectoryInfo source, DirectoryInfo target, DirectoryInfo exclude)
{
Directory.CreateDirectory(target.FullName);
foreach (var fileInfo in source.GetFiles())
{
var path = Path.Combine(target.FullName, fileInfo.Name);
_task.Log.LogMessage($"Copying file from: {fileInfo.FullName}");
_task.Log.LogMessage($"Copying to destination: {path}");
fileInfo.CopyTo(path, true);
}
foreach (var sourceSubDir in source.GetDirectories())
{
if (sourceSubDir.FullName != exclude.FullName)
{
var targetSubDir = target.CreateSubdirectory(sourceSubDir.Name);
CopyFiles(sourceSubDir, targetSubDir, exclude);
}
}
}
19
Source : Util.cs
with Apache License 2.0
from Epi-Info
with Apache License 2.0
from Epi-Info
public static void CopyDirectory(DirectoryInfo source, DirectoryInfo target)
{
if (Directory.Exists(target.FullName) == false)
{
Directory.CreateDirectory(target.FullName);
}
foreach (FileInfo fi in source.GetFiles())
{
fi.CopyTo(Path.Combine(target.ToString(), fi.Name), true);
}
foreach (DirectoryInfo diSourceSubDir in source.GetDirectories())
{
DirectoryInfo nextTargetSubDir =
target.CreateSubdirectory(diSourceSubDir.Name);
CopyDirectory(diSourceSubDir, nextTargetSubDir);
}
}
19
Source : TestProjectDuplicator.cs
with GNU General Public License v3.0
from Faultify
with GNU General Public License v3.0
from Faultify
private static void CopyFilesRecursively(DirectoryInfo source, DirectoryInfo target)
{
foreach (var dir in source.GetDirectories())
CopyFilesRecursively(dir, target.CreateSubdirectory(dir.Name));
foreach (var file in source.GetFiles())
file.CopyTo(Path.Combine(target.FullName, file.Name));
}
19
Source : RemoveEmptyFolderTests.cs
with MIT License
from GarfieldJiang
with MIT License
from GarfieldJiang
[Test]
public void Normal()
{
var a = m_Root.CreateSubdirectory("a");
var b = m_Root.CreateSubdirectory("b");
var c = b.CreateSubdirectory("c");
var d = m_Root.CreateSubdirectory("d");
var e = d.CreateSubdirectory("e");
var fileA = new FileInfo(Path.Combine(d.FullName, "a"));
fileA.Create().Close();
var f = m_Root.CreateSubdirectory("f");
var g = f.CreateSubdirectory("g");
var fileB = new FileInfo(Path.Combine(g.FullName, "b"));
fileB.Create().Close();
Utility.IO.DeleteEmptyFolders(m_Root);
replacedert.IsTrue(m_Root.Exists);
replacedert.IsFalse(a.Exists);
replacedert.IsFalse(b.Exists);
replacedert.IsFalse(c.Exists);
replacedert.IsTrue(d.Exists);
replacedert.IsFalse(e.Exists);
replacedert.IsTrue(f.Exists);
replacedert.IsTrue(g.Exists);
replacedert.IsTrue(fileA.Exists);
replacedert.IsTrue(fileB.Exists);
}
19
Source : main.cs
with MIT License
from gungunfebrianza
with MIT License
from gungunfebrianza
public static void CopyFilesRecursively(DirectoryInfo source, DirectoryInfo target)
{
foreach (DirectoryInfo dir in source.GetDirectories())
CopyFilesRecursively(dir, target.CreateSubdirectory(dir.Name));
foreach (FileInfo file in source.GetFiles())
file.CopyTo(Path.Combine(target.FullName, file.Name));
}
19
Source : ExtractionDestination.cs
with GNU General Public License v3.0
from HicServices
with GNU General Public License v3.0
from HicServices
private void WriteBundleContents(IExtractableDatasetBundle datasetBundle, IDataLoadEventListener job, GracefulCancellationToken cancellationToken)
{
var rootDir = GetDirectoryFor(_request);
var supportingSQLFolder = new DirectoryInfo(Path.Combine(rootDir.FullName, SupportingSQLTable.ExtractionFolderName));
var lookupDir = rootDir.CreateSubdirectory("Lookups");
//extract the doreplacedents
foreach (SupportingDoreplacedent doc in datasetBundle.Doreplacedents)
datasetBundle.States[doc] = TryExtractSupportingDoreplacedent(doc,rootDir, job)
? ExtractCommandState.Completed
: ExtractCommandState.Crashed;
//extract supporting SQL
foreach (SupportingSQLTable sql in datasetBundle.SupportingSQL)
datasetBundle.States[sql] = TryExtractSupportingSQLTable(sql,supportingSQLFolder, _request.Configuration, job, _dataLoadInfo)
? ExtractCommandState.Completed
: ExtractCommandState.Crashed;
//extract lookups
foreach (BundledLookupTable lookup in datasetBundle.LookupTables)
{
datasetBundle.States[lookup] = TryExtractLookupTable(lookup, lookupDir,job)
? ExtractCommandState.Completed
: ExtractCommandState.Crashed;
}
}
19
Source : ExtractionDirectory.cs
with GNU General Public License v3.0
from HicServices
with GNU General Public License v3.0
from HicServices
public DirectoryInfo GetGlobalsDirectory()
{
return ExtractionDirectoryInfo.CreateSubdirectory(GLOBALS_DATA_NAME);
}
19
Source : ExtractionDirectory.cs
with GNU General Public License v3.0
from HicServices
with GNU General Public License v3.0
from HicServices
public DirectoryInfo GetDirectoryForCohortCustomData()
{
return ExtractionDirectoryInfo.CreateSubdirectory(CUSTOM_COHORT_DATA_FOLDER_NAME);
}
19
Source : ExtractionDirectory.cs
with GNU General Public License v3.0
from HicServices
with GNU General Public License v3.0
from HicServices
public DirectoryInfo GetDirectoryForMasterData()
{
return ExtractionDirectoryInfo.CreateSubdirectory(MASTER_DATA_FOLDER_NAME);
}
19
Source : LoadDirectory.cs
with GNU General Public License v3.0
from HicServices
with GNU General Public License v3.0
from HicServices
public static LoadDirectory CreateDirectoryStructure(DirectoryInfo parentDir, string dirName, bool overrideExistsCheck = false)
{
if (!parentDir.Exists)
parentDir.Create();
var projectDir = new DirectoryInfo(Path.Combine(parentDir.FullName, dirName));
if (!overrideExistsCheck && projectDir.Exists && projectDir.GetFileSystemInfos().Any())
throw new Exception("The directory " + projectDir.FullName + " already exists (and we don't want to accidentally nuke anything)");
projectDir.Create();
var dataDir = projectDir.CreateSubdirectory("Data");
dataDir.CreateSubdirectory("ForLoading");
dataDir.CreateSubdirectory("ForArchiving");
dataDir.CreateSubdirectory("Cache");
StreamWriter swExampleFixedWidth = new StreamWriter(Path.Combine(dataDir.FullName, "ExampleFixedWidthFormatFile.csv"));
swExampleFixedWidth.Write(ExampleFixedWidthFormatFileContents);
swExampleFixedWidth.Flush();
swExampleFixedWidth.Close();
projectDir.CreateSubdirectory("Executables");
return new LoadDirectory(projectDir.FullName);
}
19
Source : ReleaseEngine.cs
with GNU General Public License v3.0
from HicServices
with GNU General Public License v3.0
from HicServices
protected void CutTreeRecursive(DirectoryInfo from, DirectoryInfo into, StreamWriter audit, int tabDepth)
{
//found files in current directory
foreach (FileInfo file in from.GetFiles())
{
//audit as -Filename at tab indent
AuditFileCreation(file.Name, audit, tabDepth);
file.CopyTo(Path.Combine(into.FullName, file.Name));
}
//found subdirectory
foreach (DirectoryInfo dir in from.GetDirectories())
{
//if it is not completely empty, copy it across
if (dir.GetFiles().Any() || dir.GetDirectories().Any())
{
//audit as +DirectoryName at tab indent
AuditDirectoryCreation(dir.Name, audit, tabDepth);
CutTreeRecursive(dir, into.CreateSubdirectory(dir.Name), audit, tabDepth + 1);
}
}
}
19
Source : Startup.cs
with GNU General Public License v3.0
from HicServices
with GNU General Public License v3.0
from HicServices
private void LoadMEF(ICatalogueRepository catalogueRepository, ICheckNotifier notifier)
{
DirectoryInfo downloadDirectory = catalogueRepository.MEF.DownloadDirectory;
//make sure the MEF directory exists
if(!downloadDirectory.Exists)
downloadDirectory.Create();
var compatiblePlugins = catalogueRepository.PluginManager.GetCompatiblePlugins();
List<DirectoryInfo> dirs = new List<DirectoryInfo>();
List<DirectoryInfo> toLoad = new List<DirectoryInfo>();
//always load the current application directory
toLoad.Add(new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory));
for (int i = 0; i < compatiblePlugins.Length; i++)
{
var subDirName = compatiblePlugins[i].GetPluginDirectoryName(downloadDirectory);
var subdir = Directory.CreateDirectory(subDirName);
dirs.Add(subdir);
var existingFiles = subdir.GetFiles("*"+PackPluginRunner.PluginPackageSuffix).ToList();
//if we have not downloaded this yet
if(!existingFiles.Any(f=>f.Name.Equals(compatiblePlugins[i].Name)))
compatiblePlugins[i].LoadModulereplacedemblies.SingleOrDefault()?.Downloadreplacedembly(subdir);
else
notifier.OnCheckPerformed(new CheckEventArgs("Found existing file '" + compatiblePlugins[i].Name +"' so didn't bother downloading it.",CheckResult.Success));
foreach(var archive in subdir.GetFiles("*"+PackPluginRunner.PluginPackageSuffix).ToList())
{
//get rid of any old out dirs
var outDir = subdir.EnumerateDirectories("out").SingleOrDefault();
bool mustUnzip = true;
//if there's already an unpacked version
if(outDir != null && outDir.Exists)
{
//if the directory has no files we have to unzip - otherwise it has an unzipped version already yay
mustUnzip = !outDir.GetFiles("*.dll",SearchOption.AllDirectories).Any();
if(mustUnzip)
outDir.Delete(true);
}
else
outDir = subdir.CreateSubdirectory("out");
if(mustUnzip)
using(var zf = ZipFile.OpenRead(archive.FullName))
try
{
zf.ExtractToDirectory(outDir.FullName);
}
catch(Exception ex)
{
notifier.OnCheckPerformed(new CheckEventArgs("Could not extract Plugin to '" + outDir.FullName+"'",CheckResult.Warning,ex));
}
else
notifier.OnCheckPerformed(new CheckEventArgs("Found existing directory '" + outDir.FullName+"' so didn't bother unzipping.",CheckResult.Success));
toLoad.AddRange(_environmentInfo.GetPluginSubDirectories(outDir.CreateSubdirectory("lib"), notifier));
//tell them we downloaded it
MEFFileDownloaded(this,
new MEFFileDownloadProgressEventArgs(subdir, compatiblePlugins.Length, i + 1,
archive.Name, false, MEFFileDownloadEventStatus.Success));
}
}
//The only Directories in MEF folder should be Plugin subdirectories, any that don't correspond with a plugin should be deleted
foreach (DirectoryInfo unexpectedDirectory in downloadDirectory.GetDirectories().Where(expected=>!dirs.Any(d=>d.FullName.Equals(expected.FullName))))
{
try
{
unexpectedDirectory.Delete(true);
notifier.OnCheckPerformed(new CheckEventArgs("Deleted unreferenced plugin folder " + unexpectedDirectory.FullName, CheckResult.Success));
}
catch (Exception ex)
{
notifier.OnCheckPerformed(
new CheckEventArgs(
"Found unreferenced (no Plugin) folder " + unexpectedDirectory.FullName +
" but we were unable to delete it (possibly because it is in use, try closing all your local RDMP applications and restarting this one)",
CheckResult.Fail, ex));
}
}
replacedemblyResolver.SetupreplacedemblyResolver(toLoad.ToArray());
MEFSafeDirectoryCatalog = new SafeDirectoryCatalog(notifier, toLoad.Select(d=>d.FullName).ToArray());
catalogueRepository.MEF.Setup(MEFSafeDirectoryCatalog);
notifier.OnCheckPerformed(new CheckEventArgs("Loading Help...", CheckResult.Success));
var sw = Stopwatch.StartNew();
if(!CatalogueRepository.SuppressHelpLoading)
catalogueRepository.CommentStore.ReadComments(Environment.CurrentDirectory,"SourceCodeForSelfAwareness.zip");
sw.Stop();
notifier.OnCheckPerformed(new CheckEventArgs("Help loading took:" + sw.Elapsed, CheckResult.Success));
}
19
Source : CachingHostTests.cs
with GNU General Public License v3.0
from HicServices
with GNU General Public License v3.0
from HicServices
[Test]
public void CacheHostOutwithPermissionWindow()
{
var rootDir = new DirectoryInfo(TestContext.CurrentContext.TestDirectory);
var testDir = rootDir.CreateSubdirectory("C");
if (testDir.Exists)
Directory.Delete(testDir.FullName, true);
var loadDirectory = LoadDirectory.CreateDirectoryStructure(testDir, "Test");
var cp = WhenIHaveA<CacheProgress>();
var loadMetadata = cp.LoadProgress.LoadMetadata;
loadMetadata.LocationOfFlatFiles = loadDirectory.RootPath.FullName;
// This feels a bit nasty, but quick and much better than having the test wait for an arbitrary time period.
var listener = new ExpectedNotificationListener("Download not permitted at this time, sleeping for 60 seconds");
cp.CacheFillProgress = DateTime.Now.AddDays(-1);
cp.PermissionWindow_ID = 1;
var permissionWindow = new PermissionWindow(Repository);
permissionWindow.RequiresSynchronousAccess = true;
permissionWindow.ID = 1;
permissionWindow.Name = "Test Permission Window";
//Create a time period that we are outwith (1 hour ago to 30 minutes ago).
TimeSpan start = DateTime.Now.TimeOfDay.Subtract(new TimeSpan(0,1,0,0));
TimeSpan stop = DateTime.Now.TimeOfDay.Subtract(new TimeSpan(0,0,30,0));
permissionWindow.SetPermissionWindowPeriods(new List<PermissionWindowPeriod>(new []
{
new PermissionWindowPeriod(
(int)DateTime.Now.DayOfWeek,
start,
stop)
}));
permissionWindow.SaveToDatabase();
cp.PermissionWindow_ID = permissionWindow.ID;
cp.SaveToDatabase();
var dataFlowPipelineEngine = Mock.Of<IDataFlowPipelineEngine>();
// set SetUp a factory stub to return our engine mock
var cacheHost = new CachingHost(Repository)
{
CacheProgress = cp
};
var stopTokenSource = new CancellationTokenSource();
var abortTokenSource = new CancellationTokenSource();
var cancellationToken = new GracefulCancellationToken(stopTokenSource.Token, abortTokenSource.Token);
var task = Task.Run(() => cacheHost.Start(listener, cancellationToken), cancellationToken.CreateLinkedSource().Token);
// Don't want to cancel before the DownloadUntilFinished loop starts and we receive the first "Download not permitted at this time, sleeping for 60 seconds" message
listener.ReceivedMessage += abortTokenSource.Cancel;
try
{
task.Wait();
}
catch (AggregateException e)
{
replacedert.AreEqual(1, e.InnerExceptions.Count);
replacedert.IsInstanceOf(typeof (TaskCanceledException), e.InnerExceptions[0], e.InnerExceptions[0].Message);
}
finally
{
testDir.Delete(true);
}
}
19
Source : SimpleFileExtractorTests.cs
with GNU General Public License v3.0
from HicServices
with GNU General Public License v3.0
from HicServices
[SetUp]
public void SetUp()
{
_extractor = new SimpleFileExtractor();
_inDir = new DirectoryInfo(Path.Combine(TestContext.CurrentContext.WorkDirectory,"In"));
_outDir = new DirectoryInfo(Path.Combine(TestContext.CurrentContext.WorkDirectory,"Out"));
if(_inDir.Exists)
_inDir.Delete(true);
if(_outDir.Exists)
_outDir.Delete(true);
_inDir.Create();
_outDir.Create();
_extractor.LocationOfFiles = _inDir;
File.WriteAllText(Path.Combine(_inDir.FullName,"blah.txt"),"fff");
File.WriteAllText(Path.Combine(_inDir.FullName,"blah2.txt"),"fff");
File.WriteAllText(Path.Combine(_inDir.FullName,"Pat1.txt"),"fff");
_inDirSub1 = _inDir.CreateSubdirectory("Sub1");
_inDirSub2 = _inDir.CreateSubdirectory("Sub2");
File.WriteAllText(Path.Combine(_inDirSub1.FullName,"subBlah.txt"),"fff");
File.WriteAllText(Path.Combine(_inDirSub2.FullName,"subBlah2.txt"),"fff");
}
19
Source : ProjectChecksTestsSimple.cs
with GNU General Public License v3.0
from HicServices
with GNU General Public License v3.0
from HicServices
[Test]
public void ConfigurationFrozen_Remnants()
{
DirectoryInfo dir;
ExtractionConfiguration config;
var p = GetProjectWithConfigDirectory(out config, out dir);
//create remnant directory (empty)
var remnantDir = dir.CreateSubdirectory("Extr_" + config.ID + "20011225");
//with empty subdirectories
remnantDir.CreateSubdirectory("DMPTestCatalogue").CreateSubdirectory("Lookups");
config.IsReleased = true;//make environment think config is released
config.SaveToDatabase();
try
{
//remnant exists
replacedert.IsTrue(dir.Exists);
replacedert.IsTrue(remnantDir.Exists);
//resolve accepting deletion
new ProjectChecker(new ThrowImmediatelyActivator(RepositoryLocator),p).Check(new AcceptAllCheckNotifier());
//boom remnant doesnt exist anymore (but parent does obviously)
replacedert.IsTrue(dir.Exists);
replacedert.IsFalse(Directory.Exists(remnantDir.FullName));//cant use .Exists for some reason, c# caches answer?
}
finally
{
config.DeleteInDatabase();
p.DeleteInDatabase();
}
}
19
Source : ProjectChecksTestsSimple.cs
with GNU General Public License v3.0
from HicServices
with GNU General Public License v3.0
from HicServices
[Test]
public void ConfigurationFrozen_RemnantsWithFiles()
{
DirectoryInfo dir;
ExtractionConfiguration config;
var p = GetProjectWithConfigDirectory(out config, out dir);
//create remnant directory (empty)
var remnantDir = dir.CreateSubdirectory("Extr_" + config.ID + "20011225");
//with empty subdirectories
var lookupDir = remnantDir.CreateSubdirectory("DMPTestCatalogue").CreateSubdirectory("Lookups");
//this time put a file in
File.AppendAllLines(Path.Combine(lookupDir.FullName,"Text.txt"),new string[]{"Amagad"});
config.IsReleased = true;//make environment think config is released
config.SaveToDatabase();
try
{
var notifier = new ToMemoryCheckNotifier();
RunTestWithCleanup(p,config,notifier);
replacedert.IsTrue(notifier.Messages.Any(
m=>m.Result == CheckResult.Fail &&
Regex.IsMatch(m.Message,@"Found non-empty folder .* which is left over extracted folder after data release \(First file found was '.*[/\\]DMPTestCatalogue[/\\]Lookups[/\\]Text.txt' but there may be others\)")));
}
finally
{
remnantDir.Delete(true);
}
}
See More Examples