Here are the examples of the csharp api System.IO.Directory.Exists(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
14425 Examples
19
Source : CodeGenerate.cs
with MIT License
from 2881099
with MIT License
from 2881099
public async Task<string> Setup(TaskBuild taskBuild, List<DbTableInfo> outputTables)
{
try
{
var paths = await Task.Run(() =>
{
var config = new TemplateServiceConfiguration();
config.EncodedStringFactory = new RawStringFactory();
Engine.Razor = RazorEngineService.Create(config);
string path = string.Empty;
foreach (var templatesPath in taskBuild.Templates)
{
path = $"{taskBuild.GeneratePath}\\{taskBuild.DbName}\\{templatesPath.Replace(".tpl", "").Trim()}";
if (!Directory.Exists(path)) Directory.CreateDirectory(path);
var razorId = Guid.NewGuid().ToString("N");
var html = File.ReadAllText(Path.Combine(Environment.CurrentDirectory, "Templates", templatesPath));
Engine.Razor.Compile(html, razorId);
//开始生成操作
foreach (var table in outputTables)
{
var sw = new StringWriter();
var model = new RazorModel(taskBuild, outputTables, table);
Engine.Razor.Run(razorId, sw, null, model);
StringBuilder plus = new StringBuilder();
plus.AppendLine("//------------------------------------------------------------------------------");
plus.AppendLine("// <auto-generated>");
plus.AppendLine("// 此代码由工具生成。");
plus.AppendLine("// 运行时版本:" + Environment.Version.ToString());
plus.AppendLine("// Website: http://www.freesql.net");
plus.AppendLine("// 对此文件的更改可能会导致不正确的行为,并且如果");
plus.AppendLine("// 重新生成代码,这些更改将会丢失。");
plus.AppendLine("// </auto-generated>");
plus.AppendLine("//------------------------------------------------------------------------------");
plus.Append(sw.ToString());
plus.AppendLine();
var outPath = $"{path}\\{taskBuild.FileName.Replace("{name}", model.GetCsName(table.Name))}";
if (!string.IsNullOrEmpty(taskBuild.RemoveStr))
outPath = outPath.Replace(taskBuild.RemoveStr, "").Trim();
File.WriteAllText(outPath, plus.ToString());
}
}
return path;
});
Process.Start(paths);
return "生成成功";
}
catch (Exception ex)
{
MessageBox.Show($"生成时发生异常,请检查模版代码: {ex.Message}.");
return $"生成时发生异常,请检查模版代码: {ex.Message}.";
}
}
19
Source : FrmRazorTemplates.cs
with MIT License
from 2881099
with MIT License
from 2881099
private void buttonX1_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxX1.Text))
{
ToastNotification.ToastBackColor = Color.Red;
ToastNotification.ToastForeColor = Color.White;
ToastNotification.ToastFont = new Font("微软雅黑", 15);
ToastNotification.Show(this, "模版名称不允许为空", null, 3000, eToastGlowColor.Red, eToastPosition.TopCenter);
return;
}
string path = Path.Combine(Environment.CurrentDirectory, "Templates");
if (!Directory.Exists(path)) Directory.CreateDirectory(path);
TemplatesName = textBoxX1.Text;
TemplatesPath = Path.Combine(path, $"{textBoxX1.Text}.tpl");
if (File.Exists(TemplatesPath))
{
ToastNotification.ToastBackColor = Color.Red;
ToastNotification.ToastForeColor = Color.White;
ToastNotification.ToastFont = new Font("微软雅黑", 15);
ToastNotification.Show(this, "模版名称己存在", null, 3000, eToastGlowColor.Red, eToastPosition.TopCenter);
return;
}
using (var sr = File.Create(TemplatesPath))
{
sr.Close();
sr.Dispose();
}
this.Close();
this.DialogResult = System.Windows.Forms.DialogResult.OK;
}
19
Source : Utils.cs
with GNU General Public License v3.0
from 2dust
with GNU General Public License v3.0
from 2dust
public static string GetTempPath()
{
string _tempPath = Path.Combine(StartupPath(), "v2ray_win_temp");
if (!Directory.Exists(_tempPath))
{
Directory.CreateDirectory(_tempPath);
}
return _tempPath;
}
19
Source : Utils.cs
with GNU General Public License v3.0
from 2dust
with GNU General Public License v3.0
from 2dust
public static void SaveLog(string strreplacedle, Exception ex)
{
try
{
string path = Path.Combine(StartupPath(), "guiLogs");
string FilePath = Path.Combine(path, DateTime.Now.ToString("yyyyMMdd") + ".txt");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
if (!File.Exists(FilePath))
{
FileStream FsCreate = new FileStream(FilePath, FileMode.Create);
FsCreate.Close();
FsCreate.Dispose();
}
FileStream FsWrite = new FileStream(FilePath, FileMode.Append, FileAccess.Write);
StreamWriter SwWrite = new StreamWriter(FsWrite);
string strContent = ex.ToString();
SwWrite.WriteLine(string.Format("{0}{1}[{2}]{3}", "--------------------------------", strreplacedle, DateTime.Now.ToString("HH:mm:ss"), "--------------------------------"));
SwWrite.Write(strContent);
SwWrite.WriteLine(Environment.NewLine);
SwWrite.WriteLine(" ");
SwWrite.Flush();
SwWrite.Close();
}
catch { }
}
19
Source : PackagesConfigTest.cs
with MIT License
from 3F
with MIT License
from 3F
[Theory]
[InlineData(PackagesConfigOptions.None)]
[InlineData(PackagesConfigOptions.SilentLoading)]
public void CtorTest1(PackagesConfigOptions silentLoading)
{
replacedert.Throws<ArgumentNullException>(() => new PackagesConfig(null, PackagesConfigOptions.Default | silentLoading));
replacedert.Throws<NotSupportedException>(() =>
new PackagesConfig(TestData.ROOT + @"PackagesConfig\packages.1.txt", PackagesConfigOptions.None | silentLoading)
);
replacedert.Throws<FileNotFoundException>(() =>
{
string dst = TestData.ROOT + @"PackagesConfig\NotRealFolder";
replacedert.False(Directory.Exists(dst));
new PackagesConfig(dst, PackagesConfigOptions.Load | silentLoading);
});
replacedert.Throws<FileNotFoundException>(() =>
{
string dst = TestData.ROOT + @"PackagesConfig\folder";
replacedert.True(Directory.Exists(dst));
new PackagesConfig(dst, PackagesConfigOptions.Load | PackagesConfigOptions.PathToStorage | silentLoading);
});
}
19
Source : DirectoryUtil.cs
with MIT License
from 404Lcc
with MIT License
from 404Lcc
public static DirectoryInfo CreateDirectory(string path)
{
if (Directory.Exists(path)) return null;
return Directory.CreateDirectory(path);
}
19
Source : WebContentFolderHelper.cs
with MIT License
from 52ABP
with MIT License
from 52ABP
public static string CalculateContentRootFolder()
{
var corereplacedemblyDirectoryPath = Path.GetDirectoryName(typeof(BookListCoreModule).Getreplacedembly().Location);
if (corereplacedemblyDirectoryPath == null)
{
throw new Exception("Could not find location of Cloud.BookList.Core replacedembly!");
}
var directoryInfo = new DirectoryInfo(corereplacedemblyDirectoryPath);
while (!DirectoryContains(directoryInfo.FullName, "Cloud.BookList.sln"))
{
if (directoryInfo.Parent == null)
{
throw new Exception("Could not find content root folder!");
}
directoryInfo = directoryInfo.Parent;
}
var webMvcFolder = Path.Combine(directoryInfo.FullName, "src", "Cloud.BookList.Web.Mvc");
if (Directory.Exists(webMvcFolder))
{
return webMvcFolder;
}
var webHostFolder = Path.Combine(directoryInfo.FullName, "src", "Cloud.BookList.Web.Host");
if (Directory.Exists(webHostFolder))
{
return webHostFolder;
}
throw new Exception("Could not find root folder of the web project!");
}
19
Source : WebContentFolderHelper.cs
with MIT License
from 52ABP
with MIT License
from 52ABP
public static string CalculateContentRootFolder()
{
var corereplacedemblyDirectoryPath = Path.GetDirectoryName(typeof(PhoneBookCoreModule).Getreplacedembly().Location);
if (corereplacedemblyDirectoryPath == null)
{
throw new Exception("Could not find location of SPACore.PhoneBook.Core replacedembly!");
}
var directoryInfo = new DirectoryInfo(corereplacedemblyDirectoryPath);
while (!DirectoryContains(directoryInfo.FullName, "SPACore.PhoneBook.sln"))
{
if (directoryInfo.Parent == null)
{
throw new Exception("Could not find content root folder!");
}
directoryInfo = directoryInfo.Parent;
}
var webMvcFolder = Path.Combine(directoryInfo.FullName, "src", "SPACore.PhoneBook.Web.Mvc");
if (Directory.Exists(webMvcFolder))
{
return webMvcFolder;
}
var webHostFolder = Path.Combine(directoryInfo.FullName, "src", "SPACore.PhoneBook.Web.Host");
if (Directory.Exists(webHostFolder))
{
return webHostFolder;
}
throw new Exception("Could not find root folder of the web project!");
}
19
Source : SyntaxTreeFixerEditor.cs
with MIT License
from 71
with MIT License
from 71
protected override void Initialize(CSharpCompilation oldCompilation, CancellationToken _)
{
OptimizationLevel compilationConfiguration = oldCompilation.Options.OptimizationLevel;
if (compilationConfiguration == OptimizationLevel.Debug && !runInDebug)
return;
if (compilationConfiguration == OptimizationLevel.Release && !runInRelease)
return;
CSharpCompilation EditCompilation(CSharpCompilation compilation, CancellationToken cancellationToken)
{
int syntaxTreesLength = compilation.SyntaxTrees.Length;
string randomDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
for (int i = 0; i < syntaxTreesLength; i++)
{
SyntaxTree tree = compilation.SyntaxTrees[i];
SyntaxTree nextTree = tree;
string treePath = tree.FilePath;
SourceText source = null;
if (nextTree.Encoding == null)
{
using (MemoryStream ms = new MemoryStream())
{
using (StreamWriter writer = new StreamWriter(ms, Encoding.UTF8, 4096, leaveOpen: true))
{
nextTree.GetText(cancellationToken).Write(writer, cancellationToken);
}
ms.Position = 0;
using (StreamReader reader = new StreamReader(ms, Encoding.UTF8, false, 4096, leaveOpen: true))
{
source = SourceText.From(reader, (int)ms.Length, Encoding.UTF8);
nextTree = nextTree.WithChangedText(source);
}
}
}
if (treePath != null && oldCompilation.SyntaxTrees.FirstOrDefault(x => x.FilePath == treePath) == tree)
{
// The tree already exists as a file, and is the one the user has;
// we don't need to change anything.
if (source == null)
// No changes applied
continue;
goto Replace;
}
if (!Directory.Exists(randomDirectory))
Directory.CreateDirectory(randomDirectory);
// The tree does not exist or has been changed by an editor,
// we need to change its filepath, and write a new file.
string newPath = string.IsNullOrEmpty(treePath)
? Path.Combine(randomDirectory, Path.GetRandomFileName() + ".cs")
: Path.Combine(randomDirectory, Path.GetFileName(treePath));
nextTree = nextTree.WithFilePath(newPath);
using (FileStream fs = File.Open(newPath, FileMode.Create, FileAccess.Write))
using (StreamWriter writer = new StreamWriter(fs, nextTree.Encoding, 4096))
{
if (source == null)
source = nextTree.GetText(cancellationToken);
source.Write(writer, cancellationToken);
}
Replace:
compilation = compilation.ReplaceSyntaxTree(tree, nextTree);
}
return compilation;
}
CompilationPipeline += EditCompilation;
}
19
Source : Utility.IO.cs
with MIT License
from 7Bytes-Studio
with MIT License
from 7Bytes-Studio
public static void ExistsOrCreateFolder(string path)
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
}
19
Source : ExportingDiagramFixture.cs
with MIT License
from 8T4
with MIT License
from 8T4
protected void Setup(string path = "c4")
{
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
}
19
Source : UserCenterController.cs
with Apache License 2.0
from 91270
with Apache License 2.0
from 91270
[HttpPost]
[Authorization]
public IActionResult AvatarUpload([FromForm(Name = "file")] IFormFile file)
{
try
{
if (Convert.ToBoolean(AppSettings.Configuration["AppSettings:Demo"]))
{
return toResponse(StatusCodeType.Error, "当前为演示模式 , 您无权修改任何数据");
}
var fileExtName = Path.GetExtension(file.FileName).ToLower();
var fileName = DateTime.Now.Ticks.ToString() + fileExtName;
string[] AllowedFileExtensions = new string[] { ".jpg", ".gif", ".png", ".jpeg" };
int MaxContentLength = 1024 * 1024 * 4;
if (!AllowedFileExtensions.Contains(fileExtName))
{
return toResponse(StatusCodeType.Error, "上传失败,未经允许上传类型");
}
if (file.Length > MaxContentLength)
{
return toResponse(StatusCodeType.Error, "上传图片过大,不能超过 " + (MaxContentLength / 1024).ToString() + " MB");
}
var filePath = $"/{DateTime.Now:yyyyMMdd}/";
var avatarDirectory = $"{AppSettings.Configuration["AvatarUpload:AvatarDirectory"]}{filePath}";
if (!Directory.Exists(avatarDirectory))
{
Directory.CreateDirectory(avatarDirectory);
}
using (var stream = new FileStream($"{avatarDirectory}{fileName}", FileMode.Create))
{
file.CopyTo(stream);
}
var avatarUrl = $"{AppSettings.Configuration["AvatarUpload:AvatarUrl"]}{filePath}{fileName}";
var userSession = _tokenManager.GetSessionInfo();
#region 更新用户信息
var response = _usersService.Update(m => m.UserID == userSession.UserID, m => new Sys_Users
{
AvatarUrl = avatarUrl,
UpdateID = userSession.UserID,
UpdateName = userSession.UserName,
UpdateTime = DateTime.Now
});
#endregion
#region 更新登录会话记录
_tokenManager.RefreshSession(userSession.UserID);
#endregion
return toResponse(avatarUrl);
}
catch (Exception)
{
throw;
}
}
19
Source : DownloadManager.cs
with GNU General Public License v3.0
from 9vult
with GNU General Public License v3.0
from 9vult
public void AddMDToQueue(Manga m, dynamic chapterIDs, bool isUpdate)
{
foreach (var chapterID in chapterIDs)
{
foreach (var chapterNum in chapterID)
{
if (chapterNum.lang_code == m.settings.lang && // Correct language
(m.settings.group == "{Any}" || chapterNum.group_name == m.settings.group) && // Correct group
!IsQueueDuplicate(m, (string)chapterNum.chapter)) // Not a dupe chapter
{
if ((isUpdate && !Directory.Exists(m.mangaDirectory.FullName + "\\" + chapterNum.chapter)) || // If "update" only add if the folder doesn't exist
!isUpdate)
{
string dlUrl = "https://mangadex.org/chapter/" + chapterID.Name + "/1";
Download dl = CreateMDDownload((string)chapterNum.chapter, chapterID.Name, m, dlUrl);
Logger.Log("Adding MD to queue '" + m.name + " chapter " + dl.chapterNumber + "'");
downloadQueue.Push(dl);
downloads.Add(dl);
downloadCount++;
}
}
}
}
DownloadNextFromQueue();
}
19
Source : ExportingDiagramFixture.cs
with MIT License
from 8T4
with MIT License
from 8T4
protected static void CleanUp(string path = "c4")
{
if (Directory.Exists(path))
Directory.Delete(path, true);
}
19
Source : FrmStartPage.cs
with GNU General Public License v3.0
from 9vult
with GNU General Public License v3.0
from 9vult
public void AddManga(string api, string num, bool isUpdate)
{
string json;
if (api != null)
{
using (var wc = new System.Net.WebClient())
{
json = wc.DownloadString(api);
}
}
else
{
json = File.ReadAllText(homeFolder + "\\" + num + "\\manga.json");
}
// Deserialize the JSON file
dynamic contents = JsonConvert.DeserializeObject(json);
string mangaName = contents.manga.replacedle;
string mangaDirectory = homeFolder + "\\" + num;
if (!Directory.Exists(mangaDirectory))
{
Logger.Log("Creating directory '" + mangaDirectory + "' and related files");
Directory.CreateDirectory(mangaDirectory);
File.WriteAllText(mangaDirectory + "\\manga.json", json); // Write the JSON to a file
File.WriteAllText(mangaDirectory + "\\tracker", "1|1"); // Write initial tracking info to a file
}
File.WriteAllText(mangaDirectory + "\\downloading", ""); // Create "Downloading" file
Manga m = new Manga(mangaName, new DirectoryInfo(mangaDirectory), "1", "1");
if (!isUpdate)
{
DialogResult result = new FrmMangaSettings(m).ShowDialog();
MessageBox.Show("Downloading data...\nYou may close the Browser as you desire.");
}
m.LoadSettings();
downloadManager.AddMDToQueue(m, contents.chapter, isUpdate);
RefreshContents();
}
19
Source : KissManga.cs
with GNU General Public License v3.0
from 9vult
with GNU General Public License v3.0
from 9vult
public override Chapter[] GetUpdates()
{
List<Chapter> result = new List<Chapter>();
String[] dlc = GetDLChapters();
bool doFullSetup = true;
foreach (string chapterUrl in KissMangaHelper.GetChapterUrls(KissMangaHelper.KISS_URL + "/manga/" + mangaRoot.Name))
{
string[] urlSplits = chapterUrl.Split('/');
string chapID = urlSplits[urlSplits.Length - 1];
string chapNum = chapID.Substring(8); // remove "chapter_"
if ((!doFullSetup) || (doFullSetup && dlc == null) || (doFullSetup && dlc[0].Equals("-1")) || (doFullSetup && dlc.Contains(chapNum)))
{
if (!Directory.Exists(Path.Combine(mangaRoot.FullName, chapID)))
{
DirectoryInfo chapDir = FileHelper.CreateFolder(mangaRoot, chapID);
Chapter newchapter = new Chapter(chapDir, chapID, chapNum, doFullSetup);
chapters.Add(newchapter);
result.Add(newchapter);
}
}
}
return result.ToArray();
}
19
Source : MangaDex.cs
with GNU General Public License v3.0
from 9vult
with GNU General Public License v3.0
from 9vult
public override Chapter[] GetUpdates()
{
List<Chapter> result = new List<Chapter>();
string jsonText = MangaDexHelper.GetMangaJSON(MangaDexHelper.GetMangaUrl(GetID()));
JObject jobj = JObject.Parse(jsonText);
String[] dlc = GetDLChapters();
bool doFullSetup = true;
foreach (JProperty p in jobj["chapter"])
{
JToken value = p.Value;
if (value.Type == JTokenType.Object)
{
JObject o = (JObject)value;
string chapNum = (String)o["chapter"];
if (usergroup == "^any-group")
{
if (((string)o["lang_code"]).Equals(userlang))
{
if ((!doFullSetup) || (doFullSetup && dlc == null) || (doFullSetup && dlc[0].Equals("-1")) || (doFullSetup && dlc.Contains(chapNum)))
{
string chapID = ((JProperty)value.Parent).Name;
if (!Directory.Exists(Path.Combine(mangaRoot.FullName, chapID)))
{
DirectoryInfo chapDir = FileHelper.CreateFolder(mangaRoot, chapID);
Chapter newchapter = new Chapter(chapDir, chapID, chapNum, doFullSetup);
chapters.Add(newchapter);
result.Add(newchapter);
}
}
}
}
else
{
if (((string)o["lang_code"]).Equals(userlang) && ((string)o["group_name"]).Equals(usergroup))
{
// Console.WriteLine(chapNum);
string chapID = ((JProperty)value.Parent).Name;
if (!Directory.Exists(Path.Combine(mangaRoot.FullName, chapID)))
{
if ((!doFullSetup) || (doFullSetup && dlc == null) || (doFullSetup && dlc[0].Equals("-1")) || (doFullSetup && dlc.Contains(chapNum)))
{
DirectoryInfo chapDir = FileHelper.CreateFolder(mangaRoot, chapID);
Chapter newchapter = new Chapter(chapDir, chapID, chapNum, doFullSetup);
chapters.Add(newchapter);
result.Add(newchapter);
}
}
}
}
}
}
return result.ToArray();
}
19
Source : FrmStartPage.cs
with GNU General Public License v3.0
from 9vult
with GNU General Public License v3.0
from 9vult
public void AddHentai(string chapterID, string replacedle)
{
string hentaiDirectory = homeFolder + "\\h" + chapterID;
if (!Directory.Exists(hentaiDirectory))
{
Logger.Log("Creating directory '" + hentaiDirectory + "' and related files");
Directory.CreateDirectory(hentaiDirectory);
File.WriteAllText(hentaiDirectory + "\\tracker", "1|1"); // Write initial tracking info to a file
File.WriteAllText(hentaiDirectory + "\\replacedle", replacedle); // Write the replacedle to a file
}
File.WriteAllText(hentaiDirectory + "\\downloading", ""); // Create "Downloading" file
Manga m = new Manga("", new DirectoryInfo(hentaiDirectory), "1", "1");
DialogResult r = new FrmHentaiSettings(m).ShowDialog();
MessageBox.Show("Downloading data...\nYou may close the Browser as you desire.");
downloadManager.AddNHToQueue(m, chapterID);
RefreshContents();
}
19
Source : FrmStartPage.cs
with GNU General Public License v3.0
from 9vult
with GNU General Public License v3.0
from 9vult
private void FrmStartPage_Load(object sender, EventArgs e)
{
downloadManager = new DownloadManager(this);
if ((string)Properties.Settings.Default["homeDirectory"] == "")
{
homeFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\MikuReader";
Properties.Settings.Default["homeDirectory"] = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\MikuReader";
Properties.Settings.Default.Save();
}
else
{
homeFolder = (string)Properties.Settings.Default["homeDirectory"];
}
Logger.logFile = homeFolder + "\\log.txt";
if (Directory.Exists(homeFolder))
{
RefreshContents();
if (lstManga.Items.Count > 0)
{
lstManga.SelectedIndex = 0;
}
}
else
{
Directory.CreateDirectory(homeFolder);
}
Logger.Log("Starting Up...");
Logger.Log("Home folder is '" + homeFolder + "'");
// updater
if ((bool)Properties.Settings.Default["checkForUpdates"] == true)
{
Logger.Log("Checking for updates...");
AutoUpdater.Start("https://www.dropbox.com/s/8pf1shiotl68fqv/updateinfo.xml?raw=1");
AutoUpdater.RunUpdateAsAdmin = true;
AutoUpdater.DownloadPath = homeFolder + "\\update";
}
}
19
Source : CameraBodyEditorWindow.cs
with Apache License 2.0
from A7ocin
with Apache License 2.0
from A7ocin
private void CreateCameraBodyPrefab (GameObject go) {
string prefabNumber = "";
int prefabCount = 0;
// loop through all prefabs and break once the name does not exist
while (true) {
Object obj = Resources.Load("CameraBody/" + go.name+prefabNumber);
if (obj == null) {
if (!System.IO.Directory.Exists(
Application.dataPath + "/Resources")) {
replacedetDatabase.CreateFolder("replacedets","Resources");
}
if (!System.IO.Directory.Exists(
Application.dataPath + "/Resources/CameraBody")) {
replacedetDatabase.CreateFolder("replacedets/Resources","CameraBody");
}
go.name = go.name + prefabNumber;
PrefabUtility.CreatePrefab(
"replacedets/Resources/CameraBody/" +
go.name+".prefab",
go,
ReplacePrefabOptions.ConnectToPrefab);
break;
}
obj = null;
prefabNumber = " (" + ++prefabCount + ")";
}
}
19
Source : CamerasManager.cs
with Apache License 2.0
from A7ocin
with Apache License 2.0
from A7ocin
void Start() {
if(enableVideoSave) {
Time.captureFramerate = frameRate;
if(cameras.Count > 0) {
// crea la cartella principale nella quale verranno create una sottocartella per ogni telecamera
folder = folder + System.DateTime.Now.ToString("_yyyy-MM-dd_HH-mm-ss");
if(System.IO.Directory.Exists(folder)) {
System.IO.Directory.Delete(folder, true);
}
System.IO.Directory.CreateDirectory(folder);
// crea una sottocartella per ogni telecamera
for(int i = 0; i < cameras.Count; ++i) {
if(cameras[i].Camera) {
cameras[i].Folder = string.Format("{0}/{1}_{2}x{3}_{4}fps",
folder,
cameras[i].Name,
cameras[i].Camera.rect.width,
cameras[i].Camera.rect.height,
frameRate);
System.IO.Directory.CreateDirectory(cameras[i].Folder);
}
}
}
}
}
19
Source : DynamicDNAConverterBehaviourEditor.cs
with Apache License 2.0
from A7ocin
with Apache License 2.0
from A7ocin
private void ImportConverterDropArea(Rect dropArea, int addMethod, Action<DynamicDNAConverterBehaviour, int> callback )
{
Event evt = Event.current;
if (evt.type == EventType.DragUpdated)
{
if (dropArea.Contains(evt.mousePosition))
{
DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
}
Event.current.Use();
return;
}
if (evt.type == EventType.DragPerform)
{
if (dropArea.Contains(evt.mousePosition))
{
DragAndDrop.AcceptDrag();
UnityEngine.Object[] draggedObjects = DragAndDrop.objectReferences as UnityEngine.Object[];
for (int i = 0; i < draggedObjects.Length; i++)
{
if (draggedObjects[i])
{
GameObject tempDnaGO = draggedObjects[i] as GameObject;
DynamicDNAConverterBehaviour tempDnareplacedet = tempDnaGO.GetComponent<DynamicDNAConverterBehaviour>();
if (tempDnareplacedet)
{
callback.DynamicInvoke(tempDnareplacedet, addMethod);
continue;
}
var path = replacedetDatabase.GetreplacedetPath(draggedObjects[i]);
if (System.IO.Directory.Exists(path))
{
RecursiveScanFoldersForreplacedets(path, callback, addMethod);
}
}
}
}
Event.current.Use();
return;
}
}
19
Source : SlotLibraryEditor.cs
with Apache License 2.0
from A7ocin
with Apache License 2.0
from A7ocin
private void DropAreaGUI(Rect dropArea)
{
var evt = Event.current;
if (evt.type == EventType.DragUpdated)
{
if (dropArea.Contains(evt.mousePosition))
{
DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
}
}
if (evt.type == EventType.DragPerform)
{
if (dropArea.Contains(evt.mousePosition))
{
DragAndDrop.AcceptDrag();
UnityEngine.Object[] draggedObjects = DragAndDrop.objectReferences as UnityEngine.Object[];
for (int i = 0; i < draggedObjects.Length; i++)
{
if (draggedObjects[i])
{
SlotDatareplacedet tempSlotDatareplacedet = draggedObjects[i] as SlotDatareplacedet;
if (tempSlotDatareplacedet)
{
AddSlotDatareplacedet(tempSlotDatareplacedet);
continue;
}
var path = replacedetDatabase.GetreplacedetPath(draggedObjects[i]);
if (System.IO.Directory.Exists(path))
{
RecursiveScanFoldersForreplacedets(path);
}
}
}
}
}
}
19
Source : UmaSlotBuilderWindow.cs
with Apache License 2.0
from A7ocin
with Apache License 2.0
from A7ocin
public void EnforceFolder(ref UnityEngine.Object folderObject)
{
if (folderObject != null)
{
string destpath = replacedetDatabase.GetreplacedetPath(folderObject);
if (string.IsNullOrEmpty(destpath))
{
folderObject = null;
}
else if (!System.IO.Directory.Exists(destpath))
{
destpath = destpath.Substring(0, destpath.LastIndexOf('/'));
folderObject = replacedetDatabase.LoadMainreplacedetAtPath(destpath);
}
}
}
19
Source : UmaSlotBuilderWindow.cs
with Apache License 2.0
from A7ocin
with Apache License 2.0
from A7ocin
private void RecurseObject(Object obj, HashSet<SkinnedMeshRenderer> meshes)
{
GameObject go = obj as GameObject;
if (go != null)
{
foreach (var smr in go.GetComponentsInChildren<SkinnedMeshRenderer>(true))
{
meshes.Add(smr);
}
return;
}
var path = replacedetDatabase.GetreplacedetPath(obj);
if (!string.IsNullOrEmpty(path) && System.IO.Directory.Exists(path))
{
foreach (var guid in replacedetDatabase.Findreplacedets("t:GameObject", new string[] {path}))
{
RecurseObject(replacedetDatabase.LoadreplacedetAtPath(replacedetDatabase.GUIDToreplacedetPath(guid), typeof(GameObject)), meshes);
}
}
}
19
Source : Tracking.cs
with Apache License 2.0
from A7ocin
with Apache License 2.0
from A7ocin
void Start()
{
ss = 0;
if (SaveVideoElaborated)
{
folder = folder + System.DateTime.Now.ToString("_yyyy-MM-dd_HH-mm-ss");
if (System.IO.Directory.Exists(folder))
{
System.IO.Directory.Delete(folder, true);
}
System.IO.Directory.CreateDirectory(folder);
}
x_coordinate = 0;
y_coordinate = 0;
skipFrame = 0;
roiRect = null;
termination = new TermCriteria(TermCriteria.EPS | TermCriteria.COUNT, 10, 1);
#if UNITY_WEBGL && !UNITY_EDITOR
StartCoroutine(Utils.getFilePathAsync("blobparams.yml", (result) => {
blobparams_yml_filepath = result;
}));
#else
blobparams_yml_filepath = Utils.getFilePath("blobparams.yml");
//Debug.Log(blobparams_yml_filepath);
#endif
}
19
Source : UMAAssetIndexerEditor.cs
with Apache License 2.0
from A7ocin
with Apache License 2.0
from A7ocin
private void DropAreaGUI(Rect dropArea)
{
var evt = Event.current;
if (evt.type == EventType.DragUpdated)
{
if (dropArea.Contains(evt.mousePosition))
{
DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
}
}
if (evt.type == EventType.DragPerform)
{
if (dropArea.Contains(evt.mousePosition))
{
DragAndDrop.AcceptDrag();
AddedDuringGui.Clear();
UnityEngine.Object[] draggedObjects = DragAndDrop.objectReferences as UnityEngine.Object[];
for (int i = 0; i < draggedObjects.Length; i++)
{
if (draggedObjects[i])
{
AddedDuringGui.Add(draggedObjects[i]);
var path = replacedetDatabase.GetreplacedetPath(draggedObjects[i]);
if (System.IO.Directory.Exists(path))
{
RecursiveScanFoldersForreplacedets(path);
}
}
}
}
}
}
19
Source : OverlayLibraryEditor.cs
with Apache License 2.0
from A7ocin
with Apache License 2.0
from A7ocin
private void DropAreaGUI(Rect dropArea){
var evt = Event.current;
if(evt.type == EventType.DragUpdated){
if(dropArea.Contains(evt.mousePosition)){
DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
}
}
if(evt.type == EventType.DragPerform){
if(dropArea.Contains(evt.mousePosition)){
DragAndDrop.AcceptDrag();
UnityEngine.Object[] draggedObjects = DragAndDrop.objectReferences;
for(int i = 0; i < draggedObjects.Length; i++){
if (draggedObjects[i])
{
OverlayDatareplacedet tempOverlayData = draggedObjects[i] as OverlayDatareplacedet;
if (tempOverlayData)
{
AddOverlayData(tempOverlayData);
continue;
}
var path = replacedetDatabase.GetreplacedetPath(draggedObjects[i]);
if (System.IO.Directory.Exists(path))
{
RecursiveScanFoldersForreplacedets(path);
}
}
}
}
}
}
19
Source : FileUtils.cs
with Apache License 2.0
from A7ocin
with Apache License 2.0
from A7ocin
public static void EnsurePath(string path)
{
if (System.IO.Directory.Exists(path)) return;
System.IO.Directory.CreateDirectory(path);
}
19
Source : FileUtils.cs
with Apache License 2.0
from A7ocin
with Apache License 2.0
from A7ocin
public static string GetInternalDataStoreFolder(bool fullPath = false, bool editorOnly = true)
{
var settingsFolderPath = "";
if (fullPath)
settingsFolderPath = Path.Combine(Application.dataPath, Path.Combine("UMA", "InternalDataStore"));
else
settingsFolderPath = Path.Combine("replacedets", Path.Combine("UMA", "InternalDataStore"));
if (editorOnly)
{
settingsFolderPath = Path.Combine(settingsFolderPath, "InEditor");
}
else
{
settingsFolderPath = Path.Combine(settingsFolderPath, Path.Combine("InGame", "Resources"));
}
if (!Directory.Exists(settingsFolderPath))
Directory.CreateDirectory(settingsFolderPath);
if (fullPath)
settingsFolderPath = Path.GetFullPath(settingsFolderPath);
return settingsFolderPath;
}
19
Source : HistoryViewer.cs
with MIT License
from aabiryukov
with MIT License
from aabiryukov
[System.Diagnostics.Codereplacedysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
private void ExecViewHistory(Uri tfsCollectionUri, string sourceControlFolder)
{
// gource start arguments
string arguments;
string replacedle;
string avatarsDirectory = null;
if (m_settigs.PlayMode == VisualizationSettings.PlayModeOption.History)
{
replacedle = "History of " + sourceControlFolder;
var logFile = Path.Combine(FileUtils.GetTempPath(), "TfsHistoryLog.tmp.txt");
if (m_settigs.ViewAvatars)
{
avatarsDirectory = Path.Combine(FileUtils.GetTempPath(), "TfsHistoryLog.tmp.Avatars");
if (!Directory.Exists(avatarsDirectory))
{
Directory.CreateDirectory(avatarsDirectory);
}
}
bool historyFound;
bool hasLines;
using (var waitMessage = new WaitMessage("Connecting to Team Foundation Server...", OnCancelByUser))
{
var progress = waitMessage.CreateProgress("Loading history ({0}% done) ...");
hasLines =
TfsLogWriter.CreateGourceLogFile(
logFile,
avatarsDirectory,
tfsCollectionUri,
sourceControlFolder,
m_settigs,
ref m_canceled,
progress.SetValue
);
historyFound = progress.LastValue > 0;
progress.Done();
}
if (m_canceled)
return;
if (!hasLines)
{
MessageBox.Show(
historyFound
? "No items found.\nCheck your filters: 'User name' and 'File type'."
: "No items found.\nTry to change period of the history (From/To dates).",
"TFS History Visualization");
return;
}
arguments = string.Format(CultureInfo.InvariantCulture, " \"{0}\" ", logFile);
// Setting other history settings
arguments += " --seconds-per-day " + m_settigs.SecondsPerDay.ToString(CultureInfo.InvariantCulture);
if (m_settigs.TimeScale != VisualizationSettings.TimeScaleOption.None)
{
var optionValue = ConvertToString(m_settigs.TimeScale);
if (optionValue != null)
arguments += " --time-scale " + optionValue;
}
if (m_settigs.LoopPlayback)
{
arguments += " --loop";
}
arguments += " --file-idle-time 60"; // 60 is default in gource 0.40 and older. Since 0.41 default 0.
}
else
{
// PlayMode: Live
replacedle = "Live changes of " + sourceControlFolder;
arguments = " --realtime --log-format custom -";
arguments += " --file-idle-time 28800"; // 8 hours (work day)
}
var baseDirectory = Path.GetDirectoryName(System.Reflection.replacedembly.GetExecutingreplacedembly().Location) ??
"unknown";
if (baseDirectory.Contains("Test"))
{
baseDirectory += @"\..\..\..\VSExtension";
}
#if DEBUG
// baseDirectory = @"C:\Temp\aaaa\уи³пс\";
#endif
var gourcePath = Path.Combine(baseDirectory, @"Gource\Gource.exe");
var dataPath = Path.Combine(baseDirectory, @"Data");
// ******************************************************
// Configuring Gource command line
// ******************************************************
arguments +=
string.Format(CultureInfo.InvariantCulture, " --highlight-users --replacedle \"{0}\"", replacedle);
if (m_settigs.ViewLogo != CheckState.Unchecked)
{
var logoFile = m_settigs.ViewLogo == CheckState.Indeterminate
? Path.Combine(dataPath, "Logo.png")
: m_settigs.LogoFileName;
// fix gource unicode path problems
logoFile = FileUtils.GetShortPath(logoFile);
arguments += string.Format(CultureInfo.InvariantCulture, " --logo \"{0}\"", logoFile);
}
if (m_settigs.FullScreen)
{
arguments += " --fullscreen";
// By default gource not using full area of screen width ( It's a bug. Must be fixed in gource 0.41).
// Fixing fullscreen resolution to real full screen.
if (!m_settigs.SetResolution)
{
var screenBounds = Screen.PrimaryScreen.Bounds;
arguments += string.Format(CultureInfo.InvariantCulture, " --viewport {0}x{1}", screenBounds.Width,
screenBounds.Height);
}
}
if (m_settigs.SetResolution)
{
arguments += string.Format(CultureInfo.InvariantCulture, " --viewport {0}x{1}",
m_settigs.ResolutionWidth, m_settigs.ResolutionHeight);
}
if (m_settigs.ViewFilesExtentionMap)
{
arguments += " --key";
}
if (!string.IsNullOrEmpty(avatarsDirectory))
{
arguments += string.Format(CultureInfo.InvariantCulture, " --user-image-dir \"{0}\"", avatarsDirectory);
}
// Process "--hide" option
{
var hideItems = string.Empty;
if (!m_settigs.ViewDirNames)
{
hideItems = "dirnames";
}
if (!m_settigs.ViewFileNames)
{
if (hideItems.Length > 0) hideItems += ",";
hideItems += "filenames";
}
if (!m_settigs.ViewUserNames)
{
if (hideItems.Length > 0) hideItems += ",";
hideItems += "usernames";
}
if (hideItems.Length > 0)
arguments += " --hide " + hideItems;
}
arguments += " --max-files " + m_settigs.MaxFiles.ToString(CultureInfo.InvariantCulture);
if (SystemInformation.TerminalServerSession)
{
arguments += " --disable-bloom";
}
if (m_settigs.PlayMode == VisualizationSettings.PlayModeOption.History)
{
var si = new ProcessStartInfo(gourcePath, arguments)
{
WindowStyle = ProcessWindowStyle.Maximized,
// UseShellExecute = true
};
Process.Start(si);
}
else
{
var logReader = new VersionControlLogReader(tfsCollectionUri, sourceControlFolder, m_settigs.UsersFilter,
m_settigs.FilesFilter);
using (new WaitMessage("Connecting to Team Foundation Server..."))
{
logReader.Connect();
}
System.Threading.Tasks.Task.Factory.StartNew(() => RunLiveChangesMonitor(logReader, gourcePath, arguments));
}
}
19
Source : TestCustomizerDD.cs
with Apache License 2.0
from A7ocin
with Apache License 2.0
from A7ocin
public void ListLoadableFiles(ScrollRect ItemList)
{
var thisSubFolder = Avatar.loadPath.TrimStart('\\', '/').TrimEnd('\\', '/').Trim();//trim this at the start and the end of slashes. And then we may need to switch any slashes in the middle depending on the platform- for explode on them or something
//we can find things in resources/thisSubFolder and in persistentDataPath/thisSubFolder
//Clear the item list
ItemList.content.GetComponent<VerticalLayoutGroup>().enabled = false;//dont seem to be able to clear the content with this on...
foreach (Transform child in ItemList.content.transform)
{
Destroy(child.gameObject);
}
ItemList.content.GetComponent<VerticalLayoutGroup>().enabled = true;
//- I need to basically get rid of the other oprions in CharacterAvatars enumerator since they are effectively useless apart from in the editor
var persistentPath = Path.Combine(Application.persistentDataPath, thisSubFolder);
if (Directory.Exists(persistentPath))
{
string[] persistentDataFiles = Directory.GetFiles(persistentPath, "*.txt");
foreach (string path in persistentDataFiles)
{
GameObject thisLoadableItem = Instantiate(loadableItemPrefab) as GameObject;
thisLoadableItem.transform.SetParent(ItemList.content.transform, false);
thisLoadableItem.GetComponent<CSLoadableItem>().customizerScript = this;
thisLoadableItem.GetComponent<CSLoadableItem>().filepath = path;
thisLoadableItem.GetComponent<CSLoadableItem>().filename = Path.GetFileNameWithoutExtension(path);
thisLoadableItem.GetComponentInChildren<Text>().text = Path.GetFileNameWithoutExtension(path);
}
}
foreach (KeyValuePair<string, string> kp in (UMAContext.Instance.dynamicCharacterSystem as DynamicCharacterSystem).CharacterRecipes)
{
GameObject thisLoadableItem = Instantiate(loadableItemPrefab) as GameObject;
thisLoadableItem.transform.SetParent(ItemList.content.transform, false);
thisLoadableItem.GetComponent<CSLoadableItem>().customizerScript = this;
thisLoadableItem.GetComponent<CSLoadableItem>().filename = Path.GetFileNameWithoutExtension(kp.Key);
thisLoadableItem.GetComponentInChildren<Text>().text = Path.GetFileNameWithoutExtension(kp.Key);
}
}
19
Source : BRDFLookupTextureInspector.cs
with Apache License 2.0
from A7ocin
with Apache License 2.0
from A7ocin
private static Texture2D PersistLookupTexture (string replacedetName, Texture2D tex)
{
if (!System.IO.Directory.Exists (kDirectoryName))
System.IO.Directory.CreateDirectory (kDirectoryName);
string replacedetPath = System.IO.Path.Combine (kDirectoryName, replacedetName + "." + kExtensionName);
bool newreplacedet = !System.IO.File.Exists (replacedetPath);
System.IO.File.WriteAllBytes (replacedetPath, tex.EncodeToPNG());
replacedetDatabase.Importreplacedet (replacedetPath, ImportreplacedetOptions.ForceUpdate);
TextureImporter texSettings = replacedetImporter.GetAtPath (replacedetPath) as TextureImporter;
if (!texSettings)
{
// workaround for bug when importing first generated texture in the project
replacedetDatabase.Refresh ();
replacedetDatabase.Importreplacedet (replacedetPath, ImportreplacedetOptions.ForceUpdate);
texSettings = replacedetImporter.GetAtPath (replacedetPath) as TextureImporter;
}
texSettings.textureCompression = TextureImporterCompression.Uncompressed;
texSettings.wrapMode = TextureWrapMode.Clamp;
if (newreplacedet)
replacedetDatabase.Importreplacedet (replacedetPath, ImportreplacedetOptions.ForceUpdate);
replacedetDatabase.Refresh ();
Texture2D newTex = replacedetDatabase.LoadreplacedetAtPath (replacedetPath, typeof(Texture2D)) as Texture2D;
return newTex;
}
19
Source : FolderTree.cs
with Apache License 2.0
from AantCoder
with Apache License 2.0
from AantCoder
public static void ReCreateeTree(string rootFolder, FoldersTree folderTree)
{
foreach (var subFolder in folderTree.SubDirs)
{
// создаем под директорию
var fullNameSubDir = Path.Combine(rootFolder, subFolder.directoryName);
if (!Directory.Exists(fullNameSubDir))
{
Directory.CreateDirectory(fullNameSubDir);
}
// для каждой созданной диретории создаем её поддиреторию
foreach (var subTree in subFolder.SubDirs)
{
ReCreateeTree(fullNameSubDir, subTree);
}
}
}
19
Source : Repository.cs
with Apache License 2.0
from AantCoder
with Apache License 2.0
from AantCoder
public void Load()
{
bool needResave = false;
if (!Directory.Exists(SaveFolderDataPlayers))
Directory.CreateDirectory(SaveFolderDataPlayers);
if (!File.Exists(SaveFileName))
{
Data = new BaseContainer();
Save();
Loger.Log("Server Create Data");
}
else
{
using (var fs = File.OpenRead(SaveFileName))
{
var bf = new BinaryFormatter() { Binder = new ServerCoreSerializationBinder() };
Loger.Log("Server Load...");
Data = (BaseContainer)bf.Deserialize(fs);
//var dataVersion = Data.VersionNum;
Loger.Log("Server Version data: " + Data.Version + " Current version: " + MainHelper.VersionInfo);
if (Data.Version != MainHelper.VersionInfo || Data.VersionNum < MainHelper.VersionNum + 1)
{
convertToLastVersion();
needResave = true;
}
if (Data.Orders == null) Data.Orders = new List<OrderTrade>();
Data.UpdatePlayersAllDic();
Loger.Log("Server Load done. Users " + Data.PlayersAll.Count.ToString() + ": "
+ Data.PlayersAll.Select(p => p.Public.Login).Aggregate((string)null, (r, i) => (r == null ? "" : r + ", ") + i)
);
ChatManager.Instance.NewChatManager(Data.MaxIdChat, Data.PlayerSystem.Chats.Keys.First());
}
}
if (needResave)
Save();
ChangeData = false;
}
19
Source : FileChecker.cs
with Apache License 2.0
from AantCoder
with Apache License 2.0
from AantCoder
public static List<ModelFileInfo> GenerateHashFiles(string rootFolder, Action<string, int> onStartUpdateFolder)
{
var result = new List<ModelFileInfo>();
if (string.IsNullOrEmpty(rootFolder) || !Directory.Exists(rootFolder))
{
Loger.Log($"Directory not found {rootFolder}");
return result;
}
generateHashFiles(result, ref rootFolder, rootFolder, true);
var checkFolders = Directory.GetDirectories(rootFolder);
// Файл который есть у клиента не найден, проверяем Первую директорию
for (var i = 0; i < checkFolders.Length; i++)
{
var folder = checkFolders[i];
onStartUpdateFolder?.Invoke(folder, i);
#if DEBUG
var di = new DirectoryInfo(folder);
if ("OnlineCity".Equals(di.Name))
continue;
#endif
var checkFolder = Path.Combine(rootFolder, folder);
if (Directory.Exists(checkFolder))
{
generateHashFiles(result, ref rootFolder, checkFolder);
}
else
{
Loger.Log($"Directory not found {checkFolder}");
}
}
return result;
}
19
Source : FileChecker.cs
with Apache License 2.0
from AantCoder
with Apache License 2.0
from AantCoder
private static void restoreFolderTree(string modsDir, FoldersTree foldersTree)
{
if (foldersTree.SubDirs == null)
{
return;
}
foreach (var folder in foldersTree.SubDirs)
{
var dirName = Path.Combine(modsDir, folder.directoryName);
if (!Directory.Exists(dirName))
{
Loger.Log($"Create directory: {dirName}");
Directory.CreateDirectory(dirName);
}
// check and create subdirs
restoreFolderTree(dirName, folder);
}
}
19
Source : ServerSettings.cs
with Apache License 2.0
from AantCoder
with Apache License 2.0
from AantCoder
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
List<ValidationResult> errors = new List<ValidationResult>();
var obj = validationContext.ObjectInstance as ServerSettings;
if (obj == null)
{
errors.Add(new ValidationResult("Setup setting before"));
return errors;
}
if (obj.Port > 65535)
{
errors.Add(new ValidationResult("Port must be < 65535"));
}
if (obj.SaveInterval < 10000 || obj.SaveInterval > 100000)
{
errors.Add(new ValidationResult("Save interval must be betwen 10000 ms and 100000"));
}
if (obj.IsModsWhitelisted)
{
if (string.IsNullOrEmpty(WorkingDirectory))
{
errors.Add(new ValidationResult("Не задана рабочая директория в коде"));
}
else if (!Directory.Exists(ModsConfigsDirectoryPath))
{
errors.Add(new ValidationResult($"Directory doesn't exist ModsConfigFilePath={obj.ModsConfigsDirectoryPath}"));
}
if (!Directory.Exists(obj.ModsDirectory))
{
errors.Add(new ValidationResult($"Mods directory doesn't exist ModsDirectory={obj.ModsDirectory}"));
}
//if (!Directory.Exists(obj.SteamWorkShopModsDir))
//{
// errors.Add(new ValidationResult($"Steam Mods directory doesn't exist SteamWorkShopModsDir={obj.SteamWorkShopModsDir}"));
//}
}
return errors;
}
19
Source : DateAndSizeRollingFileAppender.cs
with MIT License
from Abc-Arbitrage
with MIT License
from Abc-Arbitrage
private void Open()
{
if (FilenameRoot == "")
throw new ArgumentException("FilenameRoot name was not supplied for RollingFileAppender");
try
{
FilenameRoot = Path.GetFullPath(FilenameRoot);
}
catch (Exception ex)
{
throw new ApplicationException("Could not resolve the full path to the log file", ex);
}
var directory = Path.GetDirectoryName(FilenameRoot) ?? throw new ApplicationException($"Could not resolve the directory of {FilenameRoot}");
if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
{
try
{
Directory.CreateDirectory(directory);
}
catch (Exception ex)
{
throw new ApplicationException($"Could not create directory for log file '{directory}'", ex);
}
}
FilenameExtension ??= "";
_rollingFileNumber = FindLastRollingFileNumber(directory);
OpenStream();
CheckRollFile(DateTime.UtcNow);
}
19
Source : SimMachine.cs
with MIT License
from abdullin
with MIT License
from abdullin
public void WipeStorage() {
var sim = Runtime.GetSimulationFolder();
var machinePath = Path.Combine(sim, Name);
if (Directory.Exists(machinePath)) {
Debug(LogType.Fault, $"ERASE STORAGE for machine {Name}");
Directory.Delete(machinePath, true);
}
}
19
Source : SimRuntime.cs
with MIT License
from abdullin
with MIT License
from abdullin
public string GetSimulationFolder() {
if (_folder != null) {
return _folder;
}
// HINT: create a memory disk here
var root = "/Volumes/SimDisk";
if (!Directory.Exists(root)) {
root = Path.GetTempPath();
}
var folder = Path.Combine(root, "sim", DateTime.UtcNow.ToString("yy-MM-dd-HH-mm-ss"));
_folder = folder;
return folder;
}
19
Source : SimMachine.cs
with MIT License
from abdullin
with MIT License
from abdullin
public string GetServiceFolder(string service, string name) {
var sim = Runtime.GetSimulationFolder();
var folder = Path.Combine(Name, $"{service}_{name}");
var localPath = Path.Combine(sim, folder);
if (!Directory.Exists(localPath)) {
Debug(LogType.RuntimeInfo, $"Allocating folder {folder}");
Directory.CreateDirectory(localPath);
} else {
Debug(LogType.RuntimeInfo, $"Reusing folder {folder}");
}
return localPath;
}
19
Source : ScriptableObjectExtensions.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
public static ScriptableObject Createreplacedet(this ScriptableObject scriptableObject, string path = null, string fileName = null)
{
var name = string.IsNullOrEmpty(fileName) ? $"{scriptableObject.GetType().Name}" : fileName;
if (string.IsNullOrEmpty(path))
{
path = "replacedets";
}
if (Path.GetExtension(path) != string.Empty)
{
var subtractedPath = path.Substring(path.LastIndexOf("/", StringComparison.Ordinal));
path = path.Replace(subtractedPath, string.Empty);
}
if (!Directory.Exists(Path.GetFullPath(path)))
{
Directory.CreateDirectory(Path.GetFullPath(path));
}
string replacedetPathAndName = replacedetDatabase.GenerateUniquereplacedetPath($"{path}/{name}.replacedet");
replacedetDatabase.Createreplacedet(scriptableObject, replacedetPathAndName);
replacedetDatabase.Savereplacedets();
replacedetDatabase.Refresh();
EditorGUIUtility.PingObject(scriptableObject);
return scriptableObject;
}
19
Source : MixedRealityToolkitFiles.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
private static void TryToCreateGeneratedFolder()
{
// Always add the MixedRealityToolkit.Generated folder to replacedets
var generatedDirs = GetDirectories(MixedRealityToolkitModuleType.Generated);
if (generatedDirs == null || !generatedDirs.Any())
{
string generatedFolderPath = Path.Combine("replacedets", "MixedRealityToolkit.Generated");
if (!Directory.Exists(generatedFolderPath))
{
Directory.CreateDirectory(generatedFolderPath);
}
string generatedSentinelFilePath = Path.Combine(generatedFolderPath, "MRTK.Generated.sentinel");
if (!File.Exists(generatedSentinelFilePath))
{
// Make sure we create and dispose/close the filestream just created
using (var f = File.Create(generatedSentinelFilePath)) { }
}
TryRegisterModuleViaFile(generatedSentinelFilePath);
}
}
19
Source : LeapMotionConfigurationChecker.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
private static void RemoveTestingFolders()
{
// If one of the leap test directories exists, then we replacedume the rest have not been deleted
if (Directory.Exists(Path.Combine(Application.dataPath, pathDifference, pathsToDelete[0])))
{
foreach (string path in pathsToDelete)
{
// Get the full path including the path difference in case the core replacedets are not imported to the root of the project
string fullPath = Path.Combine(Application.dataPath, pathDifference, path);
// If we are deleting a specific file, then we also need to remove the meta replacedociated with the file
if (File.Exists(fullPath) && fullPath.Contains(".cs"))
{
// Delete the test files
FileUtil.DeleteFileOrDirectory(fullPath);
// Also delete the meta files
FileUtil.DeleteFileOrDirectory(fullPath + ".meta");
}
if (Directory.Exists(fullPath))
{
// Delete the test directories
FileUtil.DeleteFileOrDirectory(fullPath);
// Delete the test directories meta files
FileUtil.DeleteFileOrDirectory(fullPath.TrimEnd('/') + ".meta");
}
}
}
}
19
Source : MixedRealityToolkitFiles.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
private static string MapRelativePathToAbsolutePath(SearchType searchType, MixedRealityToolkitModuleType module, string mrtkPath)
{
if (!AreFoldersAvailable)
{
Debug.LogWarning("Failed to locate MixedRealityToolkit folders in the project.");
return null;
}
mrtkPath = NormalizeSeparators(mrtkPath);
if (mrtkFolders.TryGetValue(module, out HashSet<string> modFolders))
{
string path = modFolders
.Select(t => Path.Combine(t, mrtkPath))
.FirstOrDefault(t => searchType == SearchType.File ? File.Exists(t) : Directory.Exists(t));
return path;
}
return null;
}
19
Source : UnityPlayerBuildTools.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
public static async Task<bool> RestoreNugetPackagesAsync(string nugetPath, string storePath)
{
Debug.replacedert(File.Exists(nugetPath));
Debug.replacedert(Directory.Exists(storePath));
string projectJSONPath = Path.Combine(storePath, "project.json");
string projectJSONLockPath = Path.Combine(storePath, "project.lock.json");
await new Process().StartProcessAsync(nugetPath, $"restore \"{projectJSONPath}\"");
return File.Exists(projectJSONLockPath);
}
19
Source : SpatialMeshExporter.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
private static void CreateFoldersIfDoesNotExist(string folderPath)
{
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
}
19
Source : LeapMotionConfigurationChecker.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
private static void AddLeapEditorAsmDefs()
{
if (FileUtilities.FindFilesInreplacedets("LeapMotion.Core.Editor.asmdef").Length == 0)
{
foreach (KeyValuePair<string, string[]> leapAsmDef in leapEditorDirectories)
{
// Convert asmdef name to a path
string leapAsmDefPath = leapAsmDef.Key.Replace('.', '/');
string leapAsmDefFilename = string.Concat(leapAsmDef.Key, ".asmdef");
// Path for the asmdef including the filename
string fullLeapAsmDefFilePath = Path.Combine(Application.dataPath, pathDifference, leapAsmDefPath, leapAsmDefFilename);
// Path for the asmdef NOT including the filename
string fullLeapAsmDefDirectoryPath = Path.Combine(Application.dataPath, pathDifference, leapAsmDefPath);
// Make sure the directory exists within the leap core replacedets before we add the asmdef
// The leap core replacedets version 4.5.0 contains the LeapMotion/Core/Tests/Editor directory while 4.4.0 does not.
if (!File.Exists(fullLeapAsmDefFilePath) && Directory.Exists(fullLeapAsmDefDirectoryPath))
{
// Create and save the new asmdef
replacedemblyDefinition leapEditorAsmDef = new replacedemblyDefinition
{
Name = leapAsmDef.Key,
References = leapAsmDef.Value,
IncludePlatforms = new string[] { "Editor" }
};
#if !UNITY_2019_3_OR_NEWER
// In Unity 2018.4, directories that contain tests need to have a test replacedembly.
// An asmdef is added to a leap directory that contains tests for the leap core replacedets 4.5.0.
if (leapEditorAsmDef.Name.Contains("Tests"))
{
leapEditorAsmDef.OptionalUnityReferences = new string[] { "Testreplacedemblies" };
}
#endif
leapEditorAsmDef.Save(fullLeapAsmDefFilePath);
}
}
}
}
19
Source : OculusPlatformSettingsEditor.cs
with MIT License
from absurd-joy
with MIT License
from absurd-joy
public static void EnforcePluginPlatformSettings(PluginPlatform platform)
{
string path = GetPlatformPluginPath(platform);
if (!Directory.Exists(path) && !File.Exists(path))
{
path += PluginDisabledSuffix;
}
if ((Directory.Exists(path)) || (File.Exists(path)))
{
string basePath = GetCurrentProjectPath();
string relPath = path.Substring(basePath.Length + 1);
PluginImporter pi = PluginImporter.GetAtPath(relPath) as PluginImporter;
if (pi == null)
{
return;
}
// Disable support for all platforms, then conditionally enable desired support below
pi.SetCompatibleWithEditor(false);
pi.SetCompatibleWithAnyPlatform(false);
pi.SetCompatibleWithPlatform(BuildTarget.Android, false);
pi.SetCompatibleWithPlatform(BuildTarget.StandaloneWindows, false);
pi.SetCompatibleWithPlatform(BuildTarget.StandaloneWindows64, false);
pi.SetCompatibleWithPlatform(BuildTarget.StandaloneLinux64, false);
#if !UNITY_2019_2_OR_NEWER
pi.SetCompatibleWithPlatform(BuildTarget.StandaloneLinux, false);
pi.SetCompatibleWithPlatform(BuildTarget.StandaloneLinuxUniversal, false);
#endif
#if UNITY_2017_3_OR_NEWER
pi.SetCompatibleWithPlatform(BuildTarget.StandaloneOSX, false);
#else
pi.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXUniversal, false);
pi.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXIntel, false);
pi.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXIntel64, false);
#endif
switch (platform)
{
case PluginPlatform.Android32:
pi.SetCompatibleWithPlatform(BuildTarget.Android, true);
pi.SetPlatformData(BuildTarget.Android, "CPU", "ARMv7");
break;
case PluginPlatform.Android64:
pi.SetCompatibleWithPlatform(BuildTarget.Android, true);
pi.SetPlatformData(BuildTarget.Android, "CPU", "ARM64");
break;
default:
throw new ArgumentException("Attempted to enable platform support for unsupported platform: " + platform);
}
replacedetDatabase.Importreplacedet(relPath, ImportreplacedetOptions.ForceUpdate);
replacedetDatabase.Savereplacedets();
replacedetDatabase.Refresh();
replacedetDatabase.Savereplacedets();
}
}
See More Examples