Here are the examples of the csharp api System.IO.DirectoryInfo.GetFiles() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1152 Examples
19
View Source File : FauxDeployCMAgent.cs
License : GNU General Public License v3.0
Project Creator : 1RedOne
License : GNU General Public License v3.0
Project Creator : 1RedOne
public static void SendCustomDiscovery(string CMServerName, string ClientName, string SiteCode, string FilePath, ObservableCollection<CustomClientRecord> customClientRecords)
{
string ddmLocal = FilePath + "\\DDRS\\" + ClientName;
string CMddmInbox = "\\\\" + CMServerName + "\\SMS_" + SiteCode + "\\inboxes\\ddm.box\\" + ClientName + ".DDR";
DiscoveryDataRecordFile ddrF = new DiscoveryDataRecordFile("ClientFaux")
{
SiteCode = SiteCode,
Architecture = "System"
};
ddrF.AddStringProperty("Name", DdmDiscoveryFlags.Key, 32, ClientName);
ddrF.AddStringProperty("Netbios Name", DdmDiscoveryFlags.Name, 16, ClientName);
foreach (CustomClientRecord Record in customClientRecords)
{
ddrF.AddStringProperty(Record.RecordName, DdmDiscoveryFlags.None, 32, Record.RecordValue);
}
System.IO.Directory.CreateDirectory(ddmLocal);
DirectoryInfo di = new DirectoryInfo(ddmLocal);
ddrF.SerializeToFile(ddmLocal);
FileInfo file = di.GetFiles().FirstOrDefault();
File.Copy(file.FullName, CMddmInbox, true);
System.IO.Directory.Delete(ddmLocal, true);
}
19
View Source File : Form2.cs
License : MIT License
Project Creator : 200Tigersbloxed
License : MIT License
Project Creator : 200Tigersbloxed
void InstallMultiContinued()
{
statuslabel.Text = "Status: Extracting Files";
progressBar1.Value = 80;
DirectoryInfo di = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory + @"\Files");
foreach (FileInfo file in di.GetFiles())
{
string[] splitdot = file.Name.Split('.');
if (splitdot[1] == "zip")
{
ZipFile.ExtractToDirectory(AppDomain.CurrentDomain.BaseDirectory + @"\Files\" + splitdot[0] + @".zip", @"Files\" + splitdot[0]);
}
}
statuslabel.Text = "Status: Moving Files";
progressBar1.Value = 90;
foreach (DirectoryInfo dir in di.GetDirectories())
{
if (multiselected == "a")
{
if (dir.Name == "ca")
{
DirectoryInfo cadi = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory + @"\Files\ca");
if (Directory.Exists(bsl + @"\CustomAvatars"))
{
// dont u dare delete someone's custom avatars folder
}
else
{
Microsoft.VisualBasic.FileIO.FileSystem.MoveDirectory(AppDomain.CurrentDomain.BaseDirectory + @"\Files\ca\CustomAvatars", bsl + @"\CustomAvatars");
}
if (Directory.Exists(bsl + @"\DynamicOpenVR"))
{
Directory.Delete(bsl + @"\DynamicOpenVR", true);
Microsoft.VisualBasic.FileIO.FileSystem.MoveDirectory(AppDomain.CurrentDomain.BaseDirectory + @"\Files\ca\DynamicOpenVR", bsl + @"\DynamicOpenVR");
}
else
{
Microsoft.VisualBasic.FileIO.FileSystem.MoveDirectory(AppDomain.CurrentDomain.BaseDirectory + @"\Files\ca\DynamicOpenVR", bsl + @"\DynamicOpenVR");
}
foreach (DirectoryInfo cadir in cadi.GetDirectories())
{
if (cadir.Name == "Plugins")
{
// Don't move CustomAvatar's DLL
}
}
}
}
if(dir.Name == "dc")
{
DirectoryInfo dcdi = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory + @"Files\dc");
foreach (DirectoryInfo dcdir in dcdi.GetDirectories())
{
if (dcdir.Name == "Plugins")
{
foreach (FileInfo file in dcdir.GetFiles())
{
if (File.Exists(bsl + @"\Plugins\" + file.Name)) {
File.Delete(bsl + @"\Plugins\" + file.Name);
File.Move(file.FullName, bsl + @"\Plugins\" + file.Name);
}
else
{
File.Move(file.FullName, bsl + @"\Plugins\" + file.Name);
}
}
}
if (dcdir.Name == "Libs")
{
foreach (DirectoryInfo dcnativedir in dcdir.GetDirectories())
{
if (Directory.Exists(bsl + @"\Libs\Native")) {
Directory.Delete(bsl + @"\Libs\Native", true);
Microsoft.VisualBasic.FileIO.FileSystem.MoveDirectory(AppDomain.CurrentDomain.BaseDirectory + @"\Files\dc\Libs\Native", bsl + @"\Libs\Native");
}
else
{
Microsoft.VisualBasic.FileIO.FileSystem.MoveDirectory(AppDomain.CurrentDomain.BaseDirectory + @"\Files\dc\Libs\Native", bsl + @"\Libs\Native");
}
}
}
}
}
if(dir.Name == "dep")
{
DirectoryInfo depdi = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory + @"Files\dep\dep");
foreach (DirectoryInfo depdir in depdi.GetDirectories())
{
if (depdir.Name == "Plugins")
{
foreach (FileInfo file in depdir.GetFiles())
{
if (File.Exists(bsl + @"\Plugins\" + file.Name)) {
File.Delete(bsl + @"\Plugins\" + file.Name);
File.Move(file.FullName, bsl + @"\Plugins\" + file.Name);
}
else
{
File.Move(file.FullName, bsl + @"\Plugins\" + file.Name);
}
}
}
}
}
if (multiselected == "a")
{
if (dir.Name == "dovr")
{
DirectoryInfo dovrdi = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory + @"Files\dovr");
foreach (DirectoryInfo dovrdir in dovrdi.GetDirectories())
{
if (dovrdir.Name == "Plugins")
{
foreach (FileInfo file in dovrdir.GetFiles())
{
if (File.Exists(bsl + @"\Plugins\" + file.Name))
{
File.Delete(bsl + @"\Plugins\" + file.Name);
File.Move(file.FullName, bsl + @"\Plugins\" + file.Name);
}
else
{
File.Move(file.FullName, bsl + @"\Plugins\" + file.Name);
}
}
}
if (dovrdir.Name == "Libs")
{
foreach (FileInfo file in dovrdir.GetFiles())
{
if (File.Exists(bsl + @"\Libs\" + file.Name))
{
File.Delete(bsl + @"\Libs\" + file.Name);
File.Move(file.FullName, bsl + @"\Libs\" + file.Name);
}
else
{
File.Move(file.FullName, bsl + @"\Libs\" + file.Name);
}
}
}
}
}
}
if (dir.Name == "multiplayer")
{
DirectoryInfo multiplayerdi = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory + @"Files\multiplayer");
foreach (DirectoryInfo multiplayerdir in multiplayerdi.GetDirectories())
{
if (multiplayerdir.Name == "Plugins")
{
foreach (FileInfo file in multiplayerdir.GetFiles())
{
if (File.Exists(bsl + @"\Plugins\" + file.Name)) {
File.Delete(bsl + @"\Plugins\" + file.Name);
File.Move(file.FullName, bsl + @"\Plugins\" + file.Name);
}
else
{
File.Move(file.FullName, bsl + @"\Plugins\" + file.Name);
}
}
}
if (multiplayerdir.Name == "Libs")
{
foreach (FileInfo file in multiplayerdir.GetFiles())
{
if (File.Exists(bsl + @"\Libs\" + file.Name)) {
File.Delete(bsl + @"\Libs\" + file.Name);
File.Move(file.FullName, bsl + @"\Libs\" + file.Name);
}
else
{
File.Move(file.FullName, bsl + @"\Libs\" + file.Name);
}
}
}
}
}
}
if(multiselected == "a")
{
if (File.Exists(@"Files\CustomAvatar.dll"))
{
if (File.Exists(bsl + @"\Plugins\CustomAvatar.dll"))
{
File.Delete(bsl + @"\Plugins\CustomAvatar.dll");
File.Move(@"Files\CustomAvatar.dll", bsl + @"\Plugins\CustomAvatar.dll");
}
else
{
File.Move(@"Files\CustomAvatar.dll", bsl + @"\Plugins\CustomAvatar.dll");
}
}
}
statuslabel.Text = "Status: Complete!";
progressBar1.Value = 100;
allowinstalluninstall = true;
currentlyinstallinguninstalling = false;
button3.BackColor = SystemColors.MenuHighlight;
button4.BackColor = SystemColors.MenuHighlight;
DialogResult dialogResult = MessageBox.Show("Multiplayer is installed! Would you like to exit?", "Complete!", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (dialogResult == DialogResult.Yes)
{
Application.Exit();
}
}
19
View Source File : Form2.cs
License : MIT License
Project Creator : 200Tigersbloxed
License : MIT License
Project Creator : 200Tigersbloxed
void InstallMulti()
{
statuslabel.Text = "Status: Preparing";
progressBar1.Value = 10;
allowinstalluninstall = false;
currentlyinstallinguninstalling = true;
button3.BackColor = SystemColors.GrayText;
button4.BackColor = SystemColors.GrayText;
Directory.CreateDirectory("Files");
DirectoryInfo di = new DirectoryInfo("Files");
foreach (FileInfo file in di.GetFiles())
{
file.Delete();
}
foreach (DirectoryInfo dir in di.GetDirectories())
{
dir.Delete(true);
}
Directory.CreateDirectory(@"Files\multiplayer");
Directory.CreateDirectory(@"Files\dovr");
Directory.CreateDirectory(@"Files\ca");
Directory.CreateDirectory(@"Files\dc");
Directory.CreateDirectory(@"Files\dep");
statuslabel.Text = "Status: Downloading Multiplayer 1/6";
progressBar1.Value = 20;
using (var wc = new WebClient())
{
wc.DownloadFileCompleted += new AsyncCompletedEventHandler(wc_DownloadCompleted);
wc.DownloadProgressChanged += wc_DownloadProgressChanged;
if(multiselected == "a") {
if(File.Exists(bsl + @"\Plugins\BeatSaberMultiplayerLite.dll"))
{
statuslabel.Text = "Status: Failed";
allowinstalluninstall = true;
currentlyinstallinguninstalling = false;
button3.BackColor = SystemColors.MenuHighlight;
button4.BackColor = SystemColors.MenuHighlight;
MessageBox.Show("Beat Saber Multiplayer Lite is installed! Installation Failed. Please Uninstall Zingabopp's Multiplayer Lite to continue installing Andruzzzhka's Multiplayer", "Uh Oh!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
wc.DownloadFileAsync(new System.Uri("https://tigersserver.xyz/andruzzzhkalatest"), AppDomain.CurrentDomain.BaseDirectory + @"\Files\multiplayer.zip");
}
}
else if(multiselected == "z")
{
if (File.Exists(bsl + @"\Plugins\BeatSaberMultiplayer.dll"))
{
statuslabel.Text = "Status: Failed";
allowinstalluninstall = true;
currentlyinstallinguninstalling = false;
button3.BackColor = SystemColors.MenuHighlight;
button4.BackColor = SystemColors.MenuHighlight;
MessageBox.Show("Beat Saber Multiplayer is installed! Installation Failed. Please Uninstall Andruzzzhka's Multiplayer to continue installing Zingabopp's Multiplayer Lite", "Uh Oh!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
wc.DownloadFileAsync(new System.Uri("https://tigersserver.xyz/zingabopplatest"), AppDomain.CurrentDomain.BaseDirectory + @"\Files\multiplayer.zip");
}
}
}
}
19
View Source File : AppConfig.cs
License : Apache License 2.0
Project Creator : 214175590
License : Apache License 2.0
Project Creator : 214175590
public void SaveConfig(int type = 0)
{
if(type == 0 || type == 1){
try
{
string mconfig = JsonConvert.SerializeObject(MConfig, Formatting.Indented);
if (!string.IsNullOrWhiteSpace(mconfig))
{
YSTools.YSFile.writeFileByString(MainForm.CONF_DIR + MC_NAME, mconfig, false, CONFIG_KEY);
}
}
catch (Exception ex)
{
logger.Error("保存Main配置文件异常:" + ex.Message);
logger.Error("--->" + MC_NAME);
}
}
if (type == 0 || type == 2)
{
string sconfig = null, scname = null;
int index = 0;
List<string> newFiles = new List<string>();
foreach (KeyValuePair<string, SessionConfig> item in SessionConfigDict)
{
try
{
sconfig = JsonConvert.SerializeObject(item.Value, Formatting.Indented);
if (!string.IsNullOrWhiteSpace(sconfig))
{
scname = string.Format("session{0}.json", index);
YSTools.YSFile.writeFileByString(MainForm.SESSION_DIR + scname, sconfig, false, CONFIG_KEY);
newFiles.Add(scname);
index++;
}
}
catch (Exception ex)
{
logger.Error("保存Session配置文件异常:" + ex.Message);
logger.Error("--->" + item.Key);
}
}
DirectoryInfo dirs = new DirectoryInfo(MainForm.SESSION_DIR);
FileInfo[] files = dirs.GetFiles();
foreach(FileInfo file in files){
if (!newFiles.Contains(file.Name))
{
file.Delete();
}
}
}
}
19
View Source File : AppConfig.cs
License : Apache License 2.0
Project Creator : 214175590
License : Apache License 2.0
Project Creator : 214175590
public void LoadConfig()
{
// 初始化主配置
try
{
MainConfig config = null;
if (File.Exists(MainForm.CONF_DIR + MC_NAME))
{
string mconfig = YSTools.YSFile.readFileToString(MainForm.CONF_DIR + MC_NAME, false, CONFIG_KEY);
if (!string.IsNullOrWhiteSpace(mconfig))
{
config = JsonConvert.DeserializeObject<MainConfig>(mconfig);
if(null != config){
MConfig = config;
}
}
}
}
catch (Exception ex)
{
logger.Error("加载Main配置文件异常:" + ex.Message);
logger.Error("--->" + MC_NAME);
}
// 初始化session配置
SessionConfigDict = new Dictionary<string, SessionConfig>();
DirectoryInfo direct = new DirectoryInfo(MainForm.SESSION_DIR);
if (direct.Exists)
{
FileInfo[] files = direct.GetFiles();
string content = null;
SessionConfig sessionConfig = null;
foreach(FileInfo file in files){
try
{
if (file.Name.EndsWith(".json"))
{
content = YSTools.YSFile.readFileToString(file.FullName, false, CONFIG_KEY);
if (!string.IsNullOrWhiteSpace(content))
{
sessionConfig = JsonConvert.DeserializeObject<SessionConfig>(content);
if (null != sessionConfig)
{
SessionConfigDict.Add(sessionConfig.SessionId, sessionConfig);
}
}
}
}catch(Exception ex){
logger.Error("加载Session配置文件异常:" + ex.Message);
logger.Error("--->" + file.Name);
}
}
}
}
19
View Source File : SkinUtil.cs
License : Apache License 2.0
Project Creator : 214175590
License : Apache License 2.0
Project Creator : 214175590
public static void SetFormSkin(Form form)
{
int index = AppConfig.Instance.MConfig.SkinIndex;
DirectoryInfo dire = new DirectoryInfo(MainForm.APP_DIR + "\\skin");
if (dire.Exists)
{
FileInfo[] files = dire.GetFiles();
int i = 0;
foreach (FileInfo file in files)
{
if(index == i){
form.BackgroundImage = new Bitmap(file.FullName);
form.BackgroundImageLayout = ImageLayout.Stretch;
break;
}
i++;
}
}
}
19
View Source File : SettingForm.cs
License : Apache License 2.0
Project Creator : 214175590
License : Apache License 2.0
Project Creator : 214175590
private void SettingForm_Load(object sender, EventArgs e)
{
cb_showMenuBar.Checked = AppConfig.Instance.MConfig.ShowMenuBar;
cb_showStatusBar.Checked = AppConfig.Instance.MConfig.ShowStatusBar;
monitorTimer.Value = AppConfig.Instance.MConfig.MonitorTimer;
DirectoryInfo dire = new DirectoryInfo(MainForm.APP_DIR + "\\skin");
if(dire.Exists){
FileInfo[] files = dire.GetFiles();
ListViewItem item = null;
int index = 0;
foreach(FileInfo file in files){
imageList1.Images.Add(new Bitmap(file.FullName));
item = new ListViewItem();
item.Tag = index;
item.Text = file.Name;
item.ImageIndex = index;
item.Checked = index == AppConfig.Instance.MConfig.SkinIndex;
listView1.Items.Add(item);
index++;
}
}
}
19
View Source File : SftpWinForm.cs
License : Apache License 2.0
Project Creator : 214175590
License : Apache License 2.0
Project Creator : 214175590
public void LoadDirFilesToListView(string path, LoadFilesResult result = null)
{
this.BeginInvoke((MethodInvoker)delegate()
{
try
{
DirectoryInfo dire = new DirectoryInfo(path);
if(dire.Exists){
listView1.Items.Clear();
LargeImages.Images.Clear();
SmallImages.Images.Clear();
FileInfo[] files = dire.GetFiles();
DirectoryInfo[] dires = dire.GetDirectories();
Icon icon = null;
ListViewItem item = null;
ListViewItem.ListViewSubItem subItem = null;
LargeImages.Images.Add(Properties.Resources.filen_64px);
LargeImages.Images.Add(Properties.Resources.folder_64px);
SmallImages.Images.Add(Properties.Resources.filen_16px);
SmallImages.Images.Add(Properties.Resources.folder_16px);
int index = 2;
item = new ListViewItem();
item.Text = "..";
subItem = new ListViewItem.ListViewSubItem();
subItem.Text = "";
item.SubItems.Add(subItem);
subItem = new ListViewItem.ListViewSubItem();
subItem.Text = "文件夹";
item.SubItems.Add(subItem);
subItem = new ListViewItem.ListViewSubItem();
subItem.Text = "";
item.SubItems.Add(subItem);
item.ImageIndex = 1;
listView1.Items.Add(item);
foreach (DirectoryInfo file in dires)
{
item = new ListViewItem();
item.Text = file.Name;
item.Tag = file;
subItem = new ListViewItem.ListViewSubItem();
subItem.Text = "";
item.SubItems.Add(subItem);
subItem = new ListViewItem.ListViewSubItem();
subItem.Text = "文件夹";
item.SubItems.Add(subItem);
subItem = new ListViewItem.ListViewSubItem();
subItem.Text = file.LastWriteTime.ToString("yyyy-MM-dd, HH:mm:ss");
item.SubItems.Add(subItem);
item.ImageIndex = 1;
listView1.Items.Add(item);
//Console.WriteLine(file.Name + " - " + file.ToString());
}
foreach(FileInfo file in files){
if(file.Extension == ".lnk"){
continue;
}
icon = Icon.ExtractreplacedociatedIcon(file.FullName);
LargeImages.Images.Add(icon.ToBitmap());
SmallImages.Images.Add(icon.ToBitmap());
item = new ListViewItem();
item.Text = file.Name;
item.Tag = file;
subItem = new ListViewItem.ListViewSubItem();
subItem.Text = Utils.getFileSize(file.Length);
item.SubItems.Add(subItem);
subItem = new ListViewItem.ListViewSubItem();
subItem.Text = file.Extension;
item.SubItems.Add(subItem);
subItem = new ListViewItem.ListViewSubItem();
subItem.Text = file.LastWriteTime.ToString("yyyy-MM-dd, HH:mm:ss");
item.SubItems.Add(subItem);
item.ImageIndex = index++;
listView1.Items.Add(item);
//Console.WriteLine(file.Name + " - " + file.ToString());
}
if (null != result)
{
result();
}
}
else
{
MessageBox.Show(this, "目录不存在", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception e)
{
logger.Error("加载数据失败:" + e.Message, e);
}
});
}
19
View Source File : IceDeployVersionForm.cs
License : Apache License 2.0
Project Creator : 214175590
License : Apache License 2.0
Project Creator : 214175590
public void UploadWar()
{
try
{
string local_pdir = stb_local_pdir.Text;
string remote_pdir = stb_remote_pdir.Text;
string targetDir = Utils.PathEndAddSlash(Utils.PathWinToLinux(local_pdir)) + "target/";
DirectoryInfo dire = new DirectoryInfo(targetDir);
FileInfo warfile = null;
if(dire.Exists){
FileInfo[] files = dire.GetFiles();
foreach(FileInfo file in files){
if(file.Extension == ".war"){
warfile = file;
break;
}
}
}
if (null != warfile)
{
string localPath = warfile.FullName;
string remotePath = Utils.PathEndAddSlash(remote_pdir) + "package/" + warfile.Name;
monitorForm.getSftp().put(localPath, remotePath, ChannelSftp.OVERWRITE);
step = 4;
}
else
{
errorLabel.Text = "war上传失败:war包不存在,可能是打包失败";
run = false;
MessageBox.Show(this, errorLabel.Text);
}
}
catch (Exception ex)
{
errorLabel.Text = "Upload .War 异常:" + ex.Message;
run = false;
MessageBox.Show(this, errorLabel.Text);
}
}
19
View Source File : SftpForm.cs
License : Apache License 2.0
Project Creator : 214175590
License : Apache License 2.0
Project Creator : 214175590
private void ParseDireToQueue(string dir, DirectoryInfo dire)
{
FileInfo[] files = dire.GetFiles();
foreach (FileInfo file1 in files)
{
ParseFileToQueue(dir + dire.Name + "/", file1);
}
DirectoryInfo[] dires = dire.GetDirectories();
if (null != dires)
{
foreach (DirectoryInfo d in dires)
{
ParseDireToQueue(dir + dire.Name + "/", d);
}
}
}
19
View Source File : AssetBundleUtil.cs
License : MIT License
Project Creator : 404Lcc
License : MIT License
Project Creator : 404Lcc
public static List<replacedetBundleData> BuildreplacedetBundleData(replacedetBundleRule[] replacedetBundleRules)
{
List<replacedetBundleData> replacedetBundleDataList = new List<replacedetBundleData>();
List<string> replacedetNameList = new List<string>();
foreach (replacedetBundleRule item in replacedetBundleRules)
{
if (item.replacedetBundleRuleType == replacedetBundleRuleType.File)
{
FileInfo[] fileInfos = FileUtil.GetFiles(new DirectoryInfo(item.path), new List<FileInfo>());
if (fileInfos.Length == 0) continue;
List<FileInfo> fileInfoList = (from fileInfo in fileInfos where !string.IsNullOrEmpty(Path.GetExtension(fileInfo.Name)) && Path.GetExtension(fileInfo.Name) != ".meta" select fileInfo).ToList();
foreach (FileInfo fileInfo in fileInfoList)
{
string replacedetName = fileInfo.FullName.Substring(fileInfo.FullName.IndexOf("replacedets")).Replace("\\", "/");
string md5 = MD5Util.ComputeMD5(replacedetName);
replacedetBundleDataList.Add(new replacedetBundleData($"{md5}.unity3d", string.Empty, uint.MinValue, long.MinValue, new string[] { replacedetName }));
}
}
if (item.replacedetBundleRuleType == replacedetBundleRuleType.Directory)
{
DirectoryInfo[] directoryInfos = DirectoryUtil.GetDirectorys(new DirectoryInfo(item.path), new List<DirectoryInfo>());
if (directoryInfos.Length == 0) continue;
foreach (DirectoryInfo directoryInfo in directoryInfos)
{
FileInfo[] fileInfos = directoryInfo.GetFiles();
if (fileInfos.Length == 0) continue;
List<FileInfo> fileInfoList = (from fileInfo in fileInfos where !string.IsNullOrEmpty(Path.GetExtension(fileInfo.Name)) && Path.GetExtension(fileInfo.Name) != ".meta" select fileInfo).ToList();
foreach (FileInfo fileInfo in fileInfoList)
{
replacedetNameList.Add(fileInfo.FullName.Substring(fileInfo.FullName.IndexOf("replacedets")).Replace("\\", "/"));
}
if (replacedetNameList.Count > 0)
{
string replacedetName = directoryInfo.FullName.Substring(directoryInfo.FullName.IndexOf("replacedets")).Replace("\\", "/");
string md5 = MD5Util.ComputeMD5(replacedetName);
replacedetBundleDataList.Add(new replacedetBundleData($"{md5}.unity3d", string.Empty, uint.MinValue, long.MinValue, replacedetNameList.ToArray()));
replacedetNameList.Clear();
}
}
}
}
return replacedetBundleDataList;
}
19
View Source File : AssetBundleUtil.cs
License : MIT License
Project Creator : 404Lcc
License : MIT License
Project Creator : 404Lcc
public static void BuildreplacedetBundle(replacedetBundleSetting replacedetBundleSetting)
{
Dictionary<string, replacedetBundleData> replacedetBundleDataDict = new Dictionary<string, replacedetBundleData>();
Dictionary<string, replacedetBundleRuleType> replacedetBundleRuleTypeDict = new Dictionary<string, replacedetBundleRuleType>();
string path = PathUtil.GetPath(PathType.DataPath, replacedetBundleSetting.outputPath, GetPlatformForreplacedetBundle(EditorUserBuildSettings.activeBuildTarget));
foreach (DirectoryInfo item in DirectoryUtil.GetDirectorys(new DirectoryInfo(path), new List<DirectoryInfo>()))
{
item.Delete();
}
foreach (FileInfo item in FileUtil.GetFiles(new DirectoryInfo(path), new List<FileInfo>()))
{
item.Delete();
}
List<replacedetBundleBuild> replacedetBundleBuildList = new List<replacedetBundleBuild>();
foreach (replacedetBundleRule item in replacedetBundleSetting.replacedetBundleRuleList)
{
if (item.replacedetBundleRuleType == replacedetBundleRuleType.File)
{
FileInfo[] fileInfos = FileUtil.GetFiles(new DirectoryInfo(item.path), new List<FileInfo>());
if (fileInfos.Length == 0) continue;
List<FileInfo> fileInfoList = (from fileInfo in fileInfos where !string.IsNullOrEmpty(Path.GetExtension(fileInfo.Name)) && Path.GetExtension(fileInfo.Name) != ".meta" select fileInfo).ToList();
foreach (FileInfo fileInfo in fileInfoList)
{
replacedetBundleRuleTypeDict.Add(fileInfo.FullName.Substring(fileInfo.FullName.IndexOf("replacedets")).Replace("\\", "/"), replacedetBundleRuleType.File);
}
}
if (item.replacedetBundleRuleType == replacedetBundleRuleType.Directory)
{
DirectoryInfo[] directoryInfos = DirectoryUtil.GetDirectorys(new DirectoryInfo(item.path), new List<DirectoryInfo>());
if (directoryInfos.Length == 0) continue;
foreach (DirectoryInfo directoryInfo in directoryInfos)
{
FileInfo[] fileInfos = directoryInfo.GetFiles();
if (fileInfos.Length == 0) continue;
List<FileInfo> fileInfoList = (from fileInfo in fileInfos where !string.IsNullOrEmpty(Path.GetExtension(fileInfo.Name)) && Path.GetExtension(fileInfo.Name) != ".meta" select fileInfo).ToList();
foreach (FileInfo fileInfo in fileInfoList)
{
replacedetBundleRuleTypeDict.Add(fileInfo.FullName.Substring(fileInfo.FullName.IndexOf("replacedets")).Replace("\\", "/"), replacedetBundleRuleType.Directory);
}
}
}
}
foreach (replacedetBundleData item in replacedetBundleSetting.replacedetBundleDataList)
{
replacedetBundleBuildList.Add(new replacedetBundleBuild()
{
replacedetBundleName = item.replacedetBundleName,
replacedetNames = item.replacedetNames,
});
}
replacedetBundleManifest replacedetBundleManifest = BuildPipeline.BuildreplacedetBundles(path, replacedetBundleBuildList.ToArray(), BuildreplacedetBundleOptions.None, EditorUserBuildSettings.activeBuildTarget);
foreach (replacedetBundleData item in replacedetBundleSetting.replacedetBundleDataList)
{
item.replacedetBundleHash = replacedetBundleManifest.GetreplacedetBundleHash(item.replacedetBundleName).ToString();
BuildPipeline.GetCRCForreplacedetBundle($"{path}/{item.replacedetBundleName}", out item.replacedetBundleCRC);
item.fileSize = FileUtil.GetFileSize($"{path}/{item.replacedetBundleName}");
replacedetBundleDataDict.Add(Path.GetFileNameWithoutExtension(item.replacedetBundleName), item);
}
replacedetBundleConfig replacedetBundleConfig = new replacedetBundleConfig(replacedetBundleSetting.buildId, replacedetBundleDataDict, replacedetBundleRuleTypeDict);
FileUtil.Savereplacedet(path, "replacedetBundleConfig.json", JsonUtil.ToJson(replacedetBundleConfig));
if (replacedetBundleSetting.isCopyStreamingreplacedets)
{
string copyPath = PathUtil.GetPath(PathType.StreamingreplacedetsPath, "Res", GetPlatformForreplacedetBundle(EditorUserBuildSettings.activeBuildTarget));
foreach (DirectoryInfo item in DirectoryUtil.GetDirectorys(new DirectoryInfo(copyPath), new List<DirectoryInfo>()))
{
item.Delete();
}
foreach (FileInfo item in FileUtil.GetFiles(new DirectoryInfo(copyPath), new List<FileInfo>()))
{
item.Delete();
}
foreach (FileInfo item in FileUtil.GetFiles(new DirectoryInfo(path), new List<FileInfo>()))
{
if (Path.GetExtension(item.Name) == ".meta") continue;
File.Copy(item.FullName, $"{PathUtil.GetPath(PathType.StreamingreplacedetsPath, "Res", GetPlatformForreplacedetBundle(EditorUserBuildSettings.activeBuildTarget))}/{item.Name}");
}
}
replacedetDatabase.Refresh();
}
19
View Source File : FileUtil.cs
License : MIT License
Project Creator : 404Lcc
License : MIT License
Project Creator : 404Lcc
public static bool FileExist(DirectoryInfo directoryInfo)
{
if (!directoryInfo.Exists) return false;
return directoryInfo.GetFiles() != null;
}
19
View Source File : FileUtil.cs
License : MIT License
Project Creator : 404Lcc
License : MIT License
Project Creator : 404Lcc
public static FileInfo[] GetFiles(DirectoryInfo directoryInfo, List<FileInfo> fileInfoList)
{
if (directoryInfo == null) return null;
if (FileExist(directoryInfo))
{
fileInfoList.AddRange(directoryInfo.GetFiles());
}
foreach (DirectoryInfo item in directoryInfo.GetDirectories())
{
GetFiles(item, fileInfoList);
}
return fileInfoList.ToArray();
}
19
View Source File : ToolsService.cs
License : Apache License 2.0
Project Creator : 91270
License : Apache License 2.0
Project Creator : 91270
private void GetFiles(string directory, List<string> list)
{
if (string.IsNullOrEmpty(directory)) return;
DirectoryInfo d = new DirectoryInfo(directory);
FileInfo[] files = d.GetFiles();
DirectoryInfo[] directs = d.GetDirectories();
foreach (FileInfo f in files)
{
list.Add(f.FullName);
}
//获取子文件夹内的文件列表,递归遍历
foreach (DirectoryInfo dd in directs)
{
GetFiles(dd.FullName, list);
}
}
19
View Source File : DevicePortal.cs
License : Apache License 2.0
Project Creator : abist-co-ltd
License : Apache License 2.0
Project Creator : abist-co-ltd
public static async Task<bool> InstallAppAsync(string appFullPath, DeviceInfo targetDevice, bool waitForDone = true)
{
Debug.replacedert(!string.IsNullOrEmpty(appFullPath));
var isAuth = await EnsureAuthenticationAsync(targetDevice);
if (!isAuth)
{
return false;
}
Debug.Log($"Starting app install on {targetDevice.ToString()}...");
// Calculate the cert and dependency paths
string fileName = Path.GetFileName(appFullPath);
string certFullPath = Path.ChangeExtension(appFullPath, ".cer");
string certName = Path.GetFileName(certFullPath);
string arch = "ARM";
if (appFullPath.Contains("x86"))
{
arch = "x86";
}
else if (appFullPath.Contains("ARM64"))
{
arch = "ARM64";
}
string depPath = $@"{Path.GetDirectoryName(appFullPath)}\Dependencies\{arch}\";
var form = new WWWForm();
try
{
// APPX file
Debug.replacedert(appFullPath != null);
using (var stream = new FileStream(appFullPath, FileMode.Open, FileAccess.Read, FileShare.Read))
{
using (var reader = new BinaryReader(stream))
{
form.AddBinaryData(fileName, reader.ReadBytes((int)reader.BaseStream.Length), fileName);
}
}
// CERT file
Debug.replacedert(certFullPath != null);
using (var stream = new FileStream(certFullPath, FileMode.Open, FileAccess.Read, FileShare.Read))
{
using (var reader = new BinaryReader(stream))
{
form.AddBinaryData(certName, reader.ReadBytes((int)reader.BaseStream.Length), certName);
}
}
// Dependencies
IOFileInfo[] depFiles = new DirectoryInfo(depPath).GetFiles();
foreach (IOFileInfo dep in depFiles)
{
using (var stream = new FileStream(dep.FullName, FileMode.Open, FileAccess.Read, FileShare.Read))
{
using (var reader = new BinaryReader(stream))
{
string depFilename = Path.GetFileName(dep.FullName);
form.AddBinaryData(depFilename, reader.ReadBytes((int)reader.BaseStream.Length), depFilename);
}
}
}
}
catch (Exception e)
{
Debug.LogException(e);
return false;
}
// Query
string query = $"{string.Format(InstallQuery, FinalizeUrl(targetDevice.IP))}?package={UnityWebRequest.EscapeURL(fileName)}";
var response = await Rest.PostAsync(query, form, targetDevice.Authorization);
if (!response.Successful)
{
if (response.ResponseCode == 403 && await RefreshCsrfTokenAsync(targetDevice))
{
return await InstallAppAsync(appFullPath, targetDevice, waitForDone);
}
Debug.LogError($"Failed to install {fileName} on {targetDevice.ToString()}.");
return false;
}
var status = AppInstallStatus.Installing;
// Wait for done (if requested)
while (waitForDone && status == AppInstallStatus.Installing)
{
status = await GetInstallStatusAsync(targetDevice);
switch (status)
{
case AppInstallStatus.InstallSuccess:
Debug.Log($"Successfully installed {fileName} on {targetDevice.ToString()}.");
return true;
case AppInstallStatus.InstallFail:
Debug.LogError($"Failed to install {fileName} on {targetDevice.ToString()}.");
return false;
}
}
return true;
}
19
View Source File : OVRPlatformTool.cs
License : MIT License
Project Creator : absurd-joy
License : MIT License
Project Creator : absurd-joy
void OnGUI()
{
if (boldFoldoutStyle == null)
{
boldFoldoutStyle = new GUIStyle(EditorStyles.foldout);
boldFoldoutStyle.fontStyle = FontStyle.Bold;
}
EditorGUIUtility.labelWidth = DEFAULT_LABEL_WIDTH;
GUILayout.Label("OVR Platform Tool", EditorStyles.boldLabel);
this.replacedleContent.text = "OVR Platform Tool";
GUIContent TargetPlatformLabel = new GUIContent("Target Oculus Platform");
OVRPlatformToolSettings.TargetPlatform = (TargetPlatform)MakeEnumPopup(TargetPlatformLabel, OVRPlatformToolSettings.TargetPlatform);
if (OVRPlatformToolSettings.TargetPlatform == TargetPlatform.None)
return;
SetOVRProjectConfig(OVRPlatformToolSettings.TargetPlatform);
SetDirtyOnGUIChange();
commandMenuScroll = EditorGUILayout.BeginScrollView(commandMenuScroll, GUILayout.Height(Screen.height / 2));
{
// Add the UI Form
EditorGUI.BeginChangeCheck();
GUILayout.Space(15.0f);
// App ID
GUIContent AppIDLabel = new GUIContent("Oculus Application ID [?]: ",
"This AppID will be used when uploading the build.");
OVRPlatformToolSettings.AppID = MakeTextBox(AppIDLabel, OVRPlatformToolSettings.AppID);
// App Token
GUIContent AppTokenLabel = new GUIContent("Oculus App Token [?]: ",
"You can get your app token from your app's Oculus API Dashboard.");
appToken = MakePreplacedwordBox(AppTokenLabel, appToken);
// Release Channel
GUIContent ReleaseChannelLabel = new GUIContent("Release Channel [?]: ",
"Specify the releaes channel of the new build, you can rereplacedign to other channels after upload.");
OVRPlatformToolSettings.ReleaseChannel = MakeTextBox(ReleaseChannelLabel, OVRPlatformToolSettings.ReleaseChannel);
// Releaes Note
GUIContent ReleaseNoteLabel = new GUIContent("Release Note: ");
OVRPlatformToolSettings.ReleaseNote = MakeTextBox(ReleaseNoteLabel, OVRPlatformToolSettings.ReleaseNote);
// Platform specific fields
if (OVRPlatformToolSettings.TargetPlatform == TargetPlatform.Rift)
{
GUIContent BuildDirLabel = new GUIContent("Rift Build Directory [?]: ",
"The full path to the directory containing your Rift build files.");
OVRPlatformToolSettings.RiftBuildDirectory = MakeFileDirectoryField(BuildDirLabel, OVRPlatformToolSettings.RiftBuildDirectory,
"Choose Rifle Build Directory");
GUIContent BuildVersionLabel = new GUIContent("Build Version [?]: ",
"The version number shown to users.");
OVRPlatformToolSettings.RiftBuildVersion = MakeTextBox(BuildVersionLabel, OVRPlatformToolSettings.RiftBuildVersion);
GUIContent LaunchFileLabel = new GUIContent("Launch File Path [?]: ",
"The full path to the executable that launches your app.");
OVRPlatformToolSettings.RiftLaunchFile = MakeFileDirectoryField(LaunchFileLabel, OVRPlatformToolSettings.RiftLaunchFile,
"Choose Launch File", true, "exe");
}
else
{
GUIContent ApkPathLabel = new GUIContent("Build APK File Path [?]: ",
"The full path to the APK file.");
OVRPlatformToolSettings.ApkBuildPath = MakeFileDirectoryField(ApkPathLabel, OVRPlatformToolSettings.ApkBuildPath,
"Choose APK File", true, "apk");
if (OVRPlatformToolSettings.TargetPlatform == TargetPlatform.Quest)
{
// Quest specific fields
}
}
showOptionalCommands = EditorGUILayout.Foldout(showOptionalCommands, "Optional Commands", boldFoldoutStyle);
if (showOptionalCommands)
{
IncrementIndent();
if (OVRPlatformToolSettings.TargetPlatform == TargetPlatform.Rift)
{
// Launch Parameters
GUIContent LaunchParamLabel = new GUIContent("Launch Parameters [?]: ",
"Specifies any arguments preplaceded to the launcher.");
OVRPlatformToolSettings.RiftLaunchParams = MakeTextBox(LaunchParamLabel, OVRPlatformToolSettings.RiftLaunchParams);
GUIContent FirewallExceptionLabel = new GUIContent("Firewall Exception [?]: ",
"Specifies if a Windows Firewall exception is required.");
OVRPlatformToolSettings.RiftFirewallException = MakeToggleBox(FirewallExceptionLabel, OVRPlatformToolSettings.RiftFirewallException);
GUIContent GamepadEmulationLabel = new GUIContent("Gamepad Emulation [?]: ",
"Specifies the type of gamepad emulation used by the Oculus Touch controllers.");
OVRPlatformToolSettings.RiftGamepadEmulation = (GamepadType)MakeEnumPopup(GamepadEmulationLabel, OVRPlatformToolSettings.RiftGamepadEmulation);
show2DCommands = EditorGUILayout.Foldout(show2DCommands, "2D", boldFoldoutStyle);
if (show2DCommands)
{
IncrementIndent();
// 2D Launch File
GUIContent LaunchFile2DLabel = new GUIContent("2D Launch File [?]: ",
"The full path to the executable that launches your app in 2D mode.");
OVRPlatformToolSettings.Rift2DLaunchFile = MakeFileDirectoryField(LaunchFile2DLabel, OVRPlatformToolSettings.Rift2DLaunchFile,
"Choose 2D Launch File", true, "exe");
// 2D Launch Parameters
GUIContent LaunchParam2DLabel = new GUIContent("2D Launch Parameters [?]: ",
"Specifies any arguments preplaceded to the launcher in 2D mode.");
OVRPlatformToolSettings.Rift2DLaunchParams = MakeTextBox(LaunchParam2DLabel, OVRPlatformToolSettings.Rift2DLaunchParams);
DecrementIndent();
}
showRedistCommands = EditorGUILayout.Foldout(showRedistCommands, "Redistributable Packages", boldFoldoutStyle);
if (showRedistCommands)
{
IncrementIndent();
for (int i = 0; i < OVRPlatformToolSettings.RiftRedistPackages.Count; i++)
{
GUIContent RedistPackageLabel = new GUIContent(OVRPlatformToolSettings.RiftRedistPackages[i].name);
OVRPlatformToolSettings.RiftRedistPackages[i].include = MakeToggleBox(RedistPackageLabel, OVRPlatformToolSettings.RiftRedistPackages[i].include);
}
DecrementIndent();
}
showExpansionFileCommands = EditorGUILayout.Foldout(showExpansionFileCommands, "Expansion Files", boldFoldoutStyle);
if (showExpansionFileCommands)
{
IncrementIndent();
// Language Pack Directory
GUIContent LanguagePackLabel = new GUIContent("Language Pack Directory [?]: ",
"The full path to the directory containing the language packs");
OVRPlatformToolSettings.LanguagePackDirectory = MakeFileDirectoryField(LanguagePackLabel, OVRPlatformToolSettings.LanguagePackDirectory,
"Choose Language Pack Directory");
}
}
else
{
if (OVRPlatformToolSettings.TargetPlatform == TargetPlatform.Quest)
{
// Quest specific optional fields
}
showExpansionFileCommands = EditorGUILayout.Foldout(showExpansionFileCommands, "Expansion Files", boldFoldoutStyle);
if (showExpansionFileCommands)
{
IncrementIndent();
// OBB File Path
GUIContent ObbPathLabel = new GUIContent("OBB File Path [?]: ",
"The full path to the OBB file.");
OVRPlatformToolSettings.ObbFilePath = MakeFileDirectoryField(ObbPathLabel, OVRPlatformToolSettings.ObbFilePath,
"Choose OBB File", true, "obb");
}
}
if (showExpansionFileCommands)
{
// replacedets Directory
GUIContent replacedetsDirLabel = new GUIContent("replacedets Directory [?]: ",
"The full path to the directory with DLCs for this build.");
string replacedetsDirectory = MakeFileDirectoryField(replacedetsDirLabel, OVRPlatformToolSettings.replacedetsDirectory,
"Choose replacedets Directory");
if (replacedetsDirectory != OVRPlatformToolSettings.replacedetsDirectory)
{
OVRPlatformToolSettings.replacedetsDirectory = replacedetsDirectory;
OVRPlatformToolSettings.replacedetConfigs.Clear();
if (!string.IsNullOrEmpty(OVRPlatformToolSettings.replacedetsDirectory))
{
DirectoryInfo dirInfo = new DirectoryInfo(OVRPlatformToolSettings.replacedetsDirectory);
FileInfo[] replacedetFiles = dirInfo.GetFiles();
foreach (FileInfo f in replacedetFiles)
{
OVRPlatformToolSettings.replacedetConfigs.Add(new replacedetConfig(f.Name));
}
}
EditorUtility.SetDirty(OVRPlatformToolSettings.Instance);
}
// Display bordered replacedet configuration list
GUILayout.Space(3f);
Rect rect = GUILayoutUtility.GetRect(0, GetreplacedetConfigElementHeight() + (replacedET_CONFIG_BACKGROUND_PADDING * 2),
GUILayout.ExpandWidth(true));
rect.x += (EditorGUI.indentLevel * INDENT_SPACING + 5);
rect.width -= (EditorGUI.indentLevel * INDENT_SPACING + 10);
DrawreplacedetConfigList(rect);
DecrementIndent();
}
EditorGUI.indentLevel--;
}
if (EditorGUI.EndChangeCheck())
{
EditorUtility.SetDirty(OVRPlatformToolSettings.Instance);
}
}
EditorGUILayout.EndScrollView();
GUILayout.Space(SINGLE_LINE_SPACING);
GUILayout.FlexibleSpace();
// Run OVR Lint Option
EditorGUIUtility.labelWidth = DEFAULT_LABEL_WIDTH;
GUIContent RunOvrLintLabel = new GUIContent("Run OVR Lint (Recommended) [?]: ",
"Run OVR Lint tool to ensure project is optimized for performance and meets Oculus packaging requirement for publishing.");
OVRPlatformToolSettings.RunOvrLint = MakeToggleBox(RunOvrLintLabel, OVRPlatformToolSettings.RunOvrLint);
// Add an Upload button
GUI.enabled = !activeProcess;
GUIContent btnTxt = new GUIContent("Upload");
var rt = GUILayoutUtility.GetRect(btnTxt, GUI.skin.button, GUILayout.ExpandWidth(false));
var btnYPos = rt.center.y;
rt.center = new Vector2(EditorGUIUtility.currentViewWidth / 2 - rt.width / 2 - buttonPadding, btnYPos);
if (GUI.Button(rt, btnTxt, GUI.skin.button))
{
OVRPlugin.SendEvent("oculus_platform_tool", "upload");
OVRPlatformTool.log = string.Empty;
OnUpload(OVRPlatformToolSettings.TargetPlatform);
}
// Add a cancel button
GUI.enabled = activeProcess;
btnTxt = new GUIContent("Cancel");
rt = GUILayoutUtility.GetRect(btnTxt, GUI.skin.button, GUILayout.ExpandWidth(false));
rt.center = new Vector2(EditorGUIUtility.currentViewWidth / 2 + rt.width / 2 + buttonPadding, btnYPos);
if (GUI.Button(rt, btnTxt, GUI.skin.button))
{
if (EditorUtility.DisplayDialog("Cancel Upload Process", "Are you sure you want to cancel the upload process?", "Yes", "No"))
{
if (ovrPlatUtilProcess != null)
{
ovrPlatUtilProcess.Kill();
OVRPlatformTool.log += "Upload process was canceled\n";
}
}
}
GUI.enabled = true;
GUILayout.FlexibleSpace();
GUILayout.Space(SINGLE_LINE_SPACING);
debugLogScroll = EditorGUILayout.BeginScrollView(debugLogScroll);
GUIStyle logBoxStyle = new GUIStyle();
logBoxStyle.margin.left = 5;
logBoxStyle.wordWrap = true;
logBoxStyle.normal.textColor = logBoxStyle.focused.textColor = EditorStyles.label.normal.textColor;
EditorGUILayout.SelectableLabel(OVRPlatformTool.log, logBoxStyle, GUILayout.Height(position.height - 30));
EditorGUILayout.EndScrollView();
}
19
View Source File : LootSwap.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
private static void ParseFolder(string folder, Dictionary<string, Dictionary<string, object>> files)
{
var di = new DirectoryInfo(folder);
if (!di.Exists)
{
Console.WriteLine($"{folder} not found");
return;
}
var _files = di.GetFiles();
foreach (var file in _files)
{
if (!file.Name.EndsWith(".cs"))
continue;
if (excludeList.Contains(file.Name))
continue;
var clreplacedName = file.Name.Replace(".cs", "");
var result = LootParser.ParseFile(file.FullName);
files.Add(clreplacedName, result);
}
var subfolders = di.GetDirectories();
foreach (var subfolder in subfolders)
ParseFolder(subfolder.FullName, files);
}
19
View Source File : SelfUpdater.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
private async Task DownloadLatestRunner(CancellationToken token)
{
string latestRunnerDirectory = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Work), Constants.Path.UpdateDirectory);
IOUtil.DeleteDirectory(latestRunnerDirectory, token);
Directory.CreateDirectory(latestRunnerDirectory);
int runnerSuffix = 1;
string archiveFile = null;
bool downloadSucceeded = false;
try
{
// Download the runner, using multiple attempts in order to be resilient against any networking/CDN issues
for (int attempt = 1; attempt <= Constants.RunnerDownloadRetryMaxAttempts; attempt++)
{
// Generate an available package name, and do our best effort to clean up stale local zip files
while (true)
{
if (_targetPackage.Platform.StartsWith("win"))
{
archiveFile = Path.Combine(latestRunnerDirectory, $"runner{runnerSuffix}.zip");
}
else
{
archiveFile = Path.Combine(latestRunnerDirectory, $"runner{runnerSuffix}.tar.gz");
}
try
{
// delete .zip file
if (!string.IsNullOrEmpty(archiveFile) && File.Exists(archiveFile))
{
Trace.Verbose("Deleting latest runner package zip '{0}'", archiveFile);
IOUtil.DeleteFile(archiveFile);
}
break;
}
catch (Exception ex)
{
// couldn't delete the file for whatever reason, so generate another name
Trace.Warning("Failed to delete runner package zip '{0}'. Exception: {1}", archiveFile, ex);
runnerSuffix++;
}
}
// Allow a 15-minute package download timeout, which is good enough to update the runner from a 1 Mbit/s ADSL connection.
if (!int.TryParse(Environment.GetEnvironmentVariable("GITHUB_ACTIONS_RUNNER_DOWNLOAD_TIMEOUT") ?? string.Empty, out int timeoutSeconds))
{
timeoutSeconds = 15 * 60;
}
Trace.Info($"Attempt {attempt}: save latest runner into {archiveFile}.");
using (var downloadTimeout = new CancellationTokenSource(TimeSpan.FromSeconds(timeoutSeconds)))
using (var downloadCts = CancellationTokenSource.CreateLinkedTokenSource(downloadTimeout.Token, token))
{
try
{
Trace.Info($"Download runner: begin download");
//open zip stream in async mode
using (HttpClient httpClient = new HttpClient(HostContext.CreateHttpClientHandler()))
{
if (!string.IsNullOrEmpty(_targetPackage.Token))
{
Trace.Info($"Adding authorization token ({_targetPackage.Token.Length} chars)");
httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", _targetPackage.Token);
}
Trace.Info($"Downloading {_targetPackage.DownloadUrl}");
using (FileStream fs = new FileStream(archiveFile, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: 4096, useAsync: true))
using (Stream result = await httpClient.GetStreamAsync(_targetPackage.DownloadUrl))
{
//81920 is the default used by System.IO.Stream.CopyTo and is under the large object heap threshold (85k).
await result.CopyToAsync(fs, 81920, downloadCts.Token);
await fs.FlushAsync(downloadCts.Token);
}
}
Trace.Info($"Download runner: finished download");
downloadSucceeded = true;
break;
}
catch (OperationCanceledException) when (token.IsCancellationRequested)
{
Trace.Info($"Runner download has been canceled.");
throw;
}
catch (Exception ex)
{
if (downloadCts.Token.IsCancellationRequested)
{
Trace.Warning($"Runner download has timed out after {timeoutSeconds} seconds");
}
Trace.Warning($"Failed to get package '{archiveFile}' from '{_targetPackage.DownloadUrl}'. Exception {ex}");
}
}
}
if (!downloadSucceeded)
{
throw new TaskCanceledException($"Runner package '{archiveFile}' failed after {Constants.RunnerDownloadRetryMaxAttempts} download attempts");
}
// If we got this far, we know that we've successfully downloaded the runner package
// Validate Hash Matches if it is provided
using (FileStream stream = File.OpenRead(archiveFile))
{
if (!String.IsNullOrEmpty(_targetPackage.HashValue))
{
using (SHA256 sha256 = SHA256.Create())
{
byte[] srcHashBytes = await sha256.ComputeHashAsync(stream);
var hash = PrimitiveExtensions.ConvertToHexString(srcHashBytes);
if (hash != _targetPackage.HashValue)
{
// Hash did not match, we can't recover from this, just throw
throw new Exception($"Computed runner hash {hash} did not match expected Runner Hash {_targetPackage.HashValue} for {_targetPackage.Filename}");
}
Trace.Info($"Validated Runner Hash matches {_targetPackage.Filename} : {_targetPackage.HashValue}");
}
}
}
if (archiveFile.EndsWith(".zip", StringComparison.OrdinalIgnoreCase))
{
ZipFile.ExtractToDirectory(archiveFile, latestRunnerDirectory);
}
else if (archiveFile.EndsWith(".tar.gz", StringComparison.OrdinalIgnoreCase))
{
string tar = WhichUtil.Which("tar", trace: Trace);
if (string.IsNullOrEmpty(tar))
{
throw new NotSupportedException($"tar -xzf");
}
// tar -xzf
using (var processInvoker = HostContext.CreateService<IProcessInvoker>())
{
processInvoker.OutputDataReceived += new EventHandler<ProcessDataReceivedEventArgs>((sender, args) =>
{
if (!string.IsNullOrEmpty(args.Data))
{
Trace.Info(args.Data);
}
});
processInvoker.ErrorDataReceived += new EventHandler<ProcessDataReceivedEventArgs>((sender, args) =>
{
if (!string.IsNullOrEmpty(args.Data))
{
Trace.Error(args.Data);
}
});
int exitCode = await processInvoker.ExecuteAsync(latestRunnerDirectory, tar, $"-xzf \"{archiveFile}\"", null, token);
if (exitCode != 0)
{
throw new NotSupportedException($"Can't use 'tar -xzf' extract archive file: {archiveFile}. return code: {exitCode}.");
}
}
}
else
{
throw new NotSupportedException($"{archiveFile}");
}
Trace.Info($"Finished getting latest runner package at: {latestRunnerDirectory}.");
}
finally
{
try
{
// delete .zip file
if (!string.IsNullOrEmpty(archiveFile) && File.Exists(archiveFile))
{
Trace.Verbose("Deleting latest runner package zip: {0}", archiveFile);
IOUtil.DeleteFile(archiveFile);
}
}
catch (Exception ex)
{
//it is not critical if we fail to delete the .zip file
Trace.Warning("Failed to delete runner package zip '{0}'. Exception: {1}", archiveFile, ex);
}
}
// copy latest runner into runner root folder
// copy bin from _work/_update -> bin.version under root
string binVersionDir = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Root), $"{Constants.Path.BinDirectory}.{_targetPackage.Version}");
Directory.CreateDirectory(binVersionDir);
Trace.Info($"Copy {Path.Combine(latestRunnerDirectory, Constants.Path.BinDirectory)} to {binVersionDir}.");
IOUtil.CopyDirectory(Path.Combine(latestRunnerDirectory, Constants.Path.BinDirectory), binVersionDir, token);
// copy externals from _work/_update -> externals.version under root
string externalsVersionDir = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Root), $"{Constants.Path.ExternalsDirectory}.{_targetPackage.Version}");
Directory.CreateDirectory(externalsVersionDir);
Trace.Info($"Copy {Path.Combine(latestRunnerDirectory, Constants.Path.ExternalsDirectory)} to {externalsVersionDir}.");
IOUtil.CopyDirectory(Path.Combine(latestRunnerDirectory, Constants.Path.ExternalsDirectory), externalsVersionDir, token);
// copy and replace all .sh/.cmd files
Trace.Info($"Copy any remaining .sh/.cmd files into runner root.");
foreach (FileInfo file in new DirectoryInfo(latestRunnerDirectory).GetFiles() ?? new FileInfo[0])
{
string destination = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Root), file.Name);
// Removing the file instead of just trying to overwrite it works around permissions issues on linux.
// https://github.com/actions/runner/issues/981
Trace.Info($"Copy {file.FullName} to {destination}");
IOUtil.DeleteFile(destination);
file.CopyTo(destination, true);
}
}
19
View Source File : IOUtil.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public static void CopyDirectory(string source, string target, CancellationToken cancellationToken)
{
// Validate args.
ArgUtil.Directory(source, nameof(source));
ArgUtil.NotNullOrEmpty(target, nameof(target));
ArgUtil.NotNull(cancellationToken, nameof(cancellationToken));
cancellationToken.ThrowIfCancellationRequested();
// Create the target directory.
Directory.CreateDirectory(target);
// Get the file contents of the directory to copy.
DirectoryInfo sourceDir = new DirectoryInfo(source);
foreach (FileInfo sourceFile in sourceDir.GetFiles() ?? new FileInfo[0])
{
// Check if the file already exists.
cancellationToken.ThrowIfCancellationRequested();
FileInfo targetFile = new FileInfo(Path.Combine(target, sourceFile.Name));
if (!targetFile.Exists ||
sourceFile.Length != targetFile.Length ||
sourceFile.LastWriteTime != targetFile.LastWriteTime)
{
// Copy the file.
sourceFile.CopyTo(targetFile.FullName, true);
}
}
// Copy the subdirectories.
foreach (DirectoryInfo subDir in sourceDir.GetDirectories() ?? new DirectoryInfo[0])
{
CopyDirectory(
source: subDir.FullName,
target: Path.Combine(target, subDir.Name),
cancellationToken: cancellationToken);
}
}
19
View Source File : DiagnosticLogManager.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
private List<string> GetWorkerDiagnosticLogFiles(string diagnosticFolder, DateTime jobStartTimeUtc)
{
// Get all worker log files with a timestamp equal or greater than the start of the job
var workerLogFiles = new List<string>();
var directoryInfo = new DirectoryInfo(diagnosticFolder);
// Sometimes the timing is off between the job start time and the time the worker log file is created.
// This adds a small buffer that provides some leeway in case the worker log file was created slightly
// before the time we log as job start time.
int bufferInSeconds = -30;
DateTime searchTimeUtc = jobStartTimeUtc.AddSeconds(bufferInSeconds);
foreach (FileInfo file in directoryInfo.GetFiles().Where(f => f.Name.StartsWith(Constants.Path.WorkerDiagnosticLogPrefix)))
{
// The format of the logs is:
// Worker_20171003-143110-utc.log
DateTime fileCreateTime = DateTime.ParseExact(
s: file.Name.Substring(startIndex: Constants.Path.WorkerDiagnosticLogPrefix.Length, length: DateTimeFormat.Length),
format: DateTimeFormat,
provider: CultureInfo.InvariantCulture);
if (fileCreateTime >= searchTimeUtc)
{
workerLogFiles.Add(file.FullName);
}
}
return workerLogFiles;
}
19
View Source File : DiagnosticLogManager.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
private List<string> GetRunnerDiagnosticLogFiles(string diagnosticFolder, DateTime jobStartTimeUtc)
{
// Get the newest runner log file that created just before the start of the job
var runnerLogFiles = new List<string>();
var directoryInfo = new DirectoryInfo(diagnosticFolder);
// The runner log that record the start point of the job should created before the job start time.
// The runner log may get paged if it reach size limit.
// We will only need upload 1 runner log file in 99%.
// There might be 1% we need to upload 2 runner log files.
String recentLog = null;
DateTime recentTimeUtc = DateTime.MinValue;
foreach (FileInfo file in directoryInfo.GetFiles().Where(f => f.Name.StartsWith(Constants.Path.RunnerDiagnosticLogPrefix)))
{
// The format of the logs is:
// Runner_20171003-143110-utc.log
if (DateTime.TryParseExact(
s: file.Name.Substring(startIndex: Constants.Path.RunnerDiagnosticLogPrefix.Length, length: DateTimeFormat.Length),
format: DateTimeFormat,
provider: CultureInfo.InvariantCulture,
style: DateTimeStyles.None,
result: out DateTime fileCreateTime))
{
// always add log file created after the job start.
if (fileCreateTime >= jobStartTimeUtc)
{
runnerLogFiles.Add(file.FullName);
}
else if (fileCreateTime > recentTimeUtc)
{
recentLog = file.FullName;
recentTimeUtc = fileCreateTime;
}
}
}
if (!String.IsNullOrEmpty(recentLog))
{
runnerLogFiles.Add(recentLog);
}
return runnerLogFiles;
}
19
View Source File : FileSystem.cs
License : Apache License 2.0
Project Creator : adamralph
License : Apache License 2.0
Project Creator : adamralph
private static void DeleteDirectory(string path)
{
// Directory.Delete fails if anything in the tree has the read-only attribute set. ¯\_(ツ)_/¯
ResetAttributes(new DirectoryInfo(path));
static void ResetAttributes(DirectoryInfo directory)
{
foreach (var childDirectory in directory.GetDirectories())
{
ResetAttributes(childDirectory);
}
foreach (var file in directory.GetFiles())
{
file.Attributes = FileAttributes.Normal;
}
directory.Attributes = FileAttributes.Normal;
}
Directory.Delete(path, true);
if (!SpinWait.SpinUntil(() => !Directory.Exists(path), millisecondsTimeout))
{
throw new IOException($"Failed to delete directory '{path}'.");
}
}
19
View Source File : ClonesManager.cs
License : MIT License
Project Creator : adrenak
License : MIT License
Project Creator : 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
View Source File : ClonesManager.cs
License : MIT License
Project Creator : adrenak
License : MIT License
Project Creator : adrenak
private static long GetDirectorySize(DirectoryInfo directory, bool includeNested = false,
string progressBarPrefix = "")
{
EditorUtility.DisplayProgressBar(progressBarPrefix + "Calculating size of directories...",
"Scanning '" + directory.FullName + "'...", 0f);
/// Calculate size of all files in directory.
long filesSize = directory.GetFiles().Sum((FileInfo file) => file.Length);
/// Calculate size of all nested directories.
long directoriesSize = 0;
if (includeNested)
{
IEnumerable<DirectoryInfo> nestedDirectories = directory.GetDirectories();
foreach (DirectoryInfo nestedDir in nestedDirectories)
{
directoriesSize += ClonesManager.GetDirectorySize(nestedDir, true, progressBarPrefix);
}
}
return filesSize + directoriesSize;
}
19
View Source File : MainWindow.xaml.cs
License : GNU General Public License v2.0
Project Creator : adrifcastr
License : GNU General Public License v2.0
Project Creator : adrifcastr
public async void decryptbsgnca()
{
offbtn();
startbar();
statuslabel.Content = "Decrypting Base Game NCA...";
string tmpdir = AppDomain.CurrentDomain.BaseDirectory + "\\tmp";
var di = new DirectoryInfo(tmpdir);
var result = di.GetFiles().OrderByDescending(x => x.Length).Take(1).ToList();
var larbnca = di.GetFiles().OrderByDescending(x => x.Length).Take(1).Select(x => x.FullName).ToList();
string basenca = String.Join(" ", larbnca);
string nspddir = AppDomain.CurrentDomain.BaseDirectory + "\\hactool.exe";
string replacedlkeyp = bsgreplacedlkyinput.Text;
string bsgtk = new string(replacedlkeyp.Where(c => char.IsLetter(c) || char.IsDigit(c)).ToArray());
string arg1 = @"-k keys.txt " + "--replacedlekey=" + bsgtk + " " + basenca;
string arg2 = " --plaintext=" + tmpdir + "\\NCAID_PLAIN.nca";
string arg = arg1 + arg2;
Process decrnca = new Process();
decrnca.StartInfo.FileName = nspddir;
decrnca.StartInfo.Arguments = arg;
decrnca.StartInfo.CreateNoWindow = true;
decrnca.StartInfo.UseShellExecute = false;
decrnca.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory();
decrnca.EnableRaisingEvents = true;
decrnca.Start();
await Task.Run(() => decrnca.WaitForExit());
decrnca.Close();
extractncau();
}
19
View Source File : MainWindow.xaml.cs
License : GNU General Public License v2.0
Project Creator : adrifcastr
License : GNU General Public License v2.0
Project Creator : adrifcastr
public async void applyupdate()
{
statuslabel.Content = "Merging NCA's...";
string curdir = AppDomain.CurrentDomain.BaseDirectory;
string tmpdir = AppDomain.CurrentDomain.BaseDirectory + "\\tmp";
string upddir = AppDomain.CurrentDomain.BaseDirectory + "\\upd";
string nspudir = AppDomain.CurrentDomain.BaseDirectory + "\\hactool.exe";
string basenca = tmpdir + "\\NCAID_PLAIN.nca";
var di = new DirectoryInfo(upddir);
var result = di.GetFiles().OrderByDescending(x => x.Length).Take(1).ToList();
var larupdnca = di.GetFiles().OrderByDescending(x => x.Length).Take(1).Select(x => x.FullName).ToList();
string updnca = String.Join(" ", larupdnca);
string replacedlkeyp = updreplacedlkyinput.Text;
string upgtk = new string(replacedlkeyp.Where(c => char.IsLetter(c) || char.IsDigit(c)).ToArray());
string arg1 = @"-k keys.txt " + "--replacedlekey=" + upgtk + " --basenca=" + basenca + " --section1=" + curdir + "\\romfs.bin" + " --exefsdir=";
string arg2 = tmpdir + "\\exefs " + updnca;
string arg = arg1 + arg2;
Process aplupd = new Process();
aplupd.StartInfo.FileName = nspudir;
aplupd.StartInfo.Arguments = arg;
aplupd.StartInfo.CreateNoWindow = true;
aplupd.StartInfo.UseShellExecute = false;
aplupd.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory();
aplupd.EnableRaisingEvents = true;
aplupd.Start();
await Task.Run(() => aplupd.WaitForExit());
aplupd.Close();
stopbar();
statuslabel.Content = "";
Directory.Delete(AppDomain.CurrentDomain.BaseDirectory + @"\\tmp", true);
Directory.Delete(AppDomain.CurrentDomain.BaseDirectory + @"\\upd", true);
onbtn();
System.Windows.MessageBox.Show("Update applyment finished.\nYou can now use your updated romFS via fs-mitm.");
}
19
View Source File : CityPreset.cs
License : GNU General Public License v3.0
Project Creator : aelariane
License : GNU General Public License v3.0
Project Creator : aelariane
public static SkinPreset[] GetAllPresets()
{
DirectoryInfo info = new DirectoryInfo(CityPath);
FileInfo[] files = info.GetFiles();
if (files.Length == 0)
{
return null;
}
SkinPreset[] result = new SkinPreset[files.Length];
for (int i = 0; i < files.Length; i++)
{
result[i] = new CityPreset(files[i].Name.Replace(Extension, string.Empty));
result[i].Load();
}
return result;
}
19
View Source File : CustomMapPreset.cs
License : GNU General Public License v3.0
Project Creator : aelariane
License : GNU General Public License v3.0
Project Creator : aelariane
public static SkinPreset[] GetAllPresets()
{
DirectoryInfo info = new DirectoryInfo(CustomPath);
FileInfo[] files = info.GetFiles();
if (files.Length == 0)
{
return null;
}
SkinPreset[] result = new SkinPreset[files.Length];
for (int i = 0; i < files.Length; i++)
{
result[i] = new CustomMapPreset(files[i].Name.Replace(Extension, string.Empty));
result[i].Load();
}
return result;
}
19
View Source File : ForestPreset.cs
License : GNU General Public License v3.0
Project Creator : aelariane
License : GNU General Public License v3.0
Project Creator : aelariane
public static SkinPreset[] GetAllPresets()
{
DirectoryInfo info = new DirectoryInfo(ForestPath);
FileInfo[] files = info.GetFiles();
if (files.Length == 0)
{
return null;
}
SkinPreset[] result = new SkinPreset[files.Length];
for (int i = 0; i < files.Length; i++)
{
result[i] = new ForestPreset(files[i].Name.Replace(Extension, string.Empty));
result[i].Load();
}
return result;
}
19
View Source File : HumanSkinPreset.cs
License : GNU General Public License v3.0
Project Creator : aelariane
License : GNU General Public License v3.0
Project Creator : aelariane
public static SkinPreset[] GetAllPresets()
{
DirectoryInfo info = new DirectoryInfo(HumansPath);
FileInfo[] files = info.GetFiles();
if (files.Length == 0)
{
return null;
}
SkinPreset[] result = new SkinPreset[files.Length];
for (int i = 0; i < files.Length; i++)
{
result[i] = new HumanSkinPreset(files[i].Name.Replace(Extension, string.Empty));
result[i].Load();
}
return result;
}
19
View Source File : ServerPreset.cs
License : GNU General Public License v3.0
Project Creator : aelariane
License : GNU General Public License v3.0
Project Creator : aelariane
public static ServerPreset[] LoadPresets()
{
DirectoryInfo info = new DirectoryInfo(Path);
FileInfo[] files = info.GetFiles();
if (files.Length == 0)
{
return null;
}
ServerPreset[] result = new ServerPreset[files.Length];
for (int i = 0; i < files.Length; i++)
{
result[i] = new ServerPreset(files[i].Name.Replace(Extension, string.Empty));
result[i].Load();
}
return result;
}
19
View Source File : SkyboxPreset.cs
License : GNU General Public License v3.0
Project Creator : aelariane
License : GNU General Public License v3.0
Project Creator : aelariane
public static SkinPreset[] GetAllPresets()
{
DirectoryInfo info = new DirectoryInfo(SkyboxPath);
FileInfo[] files = info.GetFiles();
if (files.Length == 0)
{
return null;
}
SkinPreset[] result = new SkinPreset[files.Length];
for (int i = 0; i < files.Length; i++)
{
result[i] = new SkyboxPreset(files[i].Name.Replace(Extension, string.Empty));
result[i].Load();
}
return result;
}
19
View Source File : TitanSkinPreset.cs
License : GNU General Public License v3.0
Project Creator : aelariane
License : GNU General Public License v3.0
Project Creator : aelariane
public static SkinPreset[] GetAllPresets()
{
DirectoryInfo info = new DirectoryInfo(replacedansPath);
FileInfo[] files = info.GetFiles();
if (files.Length == 0)
{
return null;
}
SkinPreset[] result = new SkinPreset[files.Length];
for (int i = 0; i < files.Length; i++)
{
result[i] = new replacedanSkinPreset(files[i].Name.Replace(Extension, string.Empty));
result[i].Load();
}
return result;
}
19
View Source File : ReadWrite.cs
License : GNU General Public License v3.0
Project Creator : aenemenate
License : GNU General Public License v3.0
Project Creator : aenemenate
public static void DeleteSave()
{
System.IO.DirectoryInfo di = new DirectoryInfo($@"saves\");
foreach (FileInfo file in di.GetFiles())
file.Delete();
di = new DirectoryInfo($@"saves\data");
foreach (FileInfo file in di.GetFiles())
file.Delete();
}
19
View Source File : FileExplorer.cs
License : MIT License
Project Creator : afxw
License : MIT License
Project Creator : afxw
public static FileSystemEntry[] GetFiles(string path)
{
var info = new DirectoryInfo(path);
var files = new List<string>();
return info.GetFiles().Select((file) => new FileSystemEntry(file.Name, file.FullName, file.Length, FileType.File)).ToArray();
}
19
View Source File : CertificateUtil.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
public static X509Certificate2 ImportCertificates(string path , string serialnum)
{
var x509Certificate2 = new X509Certificate2() ;
// 获取证书文件夹下所有证书
var dir = new DirectoryInfo(path) ;
var files = dir.GetFiles() ;
try
{
// 遍历所有证书的序列号,返回符合条件的证书
foreach (var fileInfo in files)
{
x509Certificate2.Import(fileInfo.FullName , "agebull" , X509KeyStorageFlags.DefaultKeySet) ;
if(serialnum == Asn1IntegerConverter.Asn1IntegerToDecimalString(x509Certificate2.GetSerialNumber()))
{
return x509Certificate2 ;
}
// 重置
x509Certificate2.Reset() ;
}
throw new ApplicationException("找不到匹配的证书!") ;
}
catch(Exception ex)
{
throw new ApplicationException(ex.Message) ;
}
}
19
View Source File : Model.cs
License : MIT License
Project Creator : AgileoAutomation
License : MIT License
Project Creator : AgileoAutomation
public void Build(DirectoryInfo dir)
{
foreach (FileInfo file in dir.GetFiles())
{
if (file.Extension == ".exe" || file.Extension == ".dll")
{
try
{
inputs.Add(new replacedemblyPointer(replacedembly.LoadFrom(file.FullName)));
}
catch (BadImageFormatException e)
{
Console.WriteLine(e.Message);
}
}
}
foreach (replacedemblyPointer pointer in inputs)
{
LoadAllReferencedreplacedemblies(pointer);
}
AddreplacedemblyPointerGroup("Model Inputs", inputs);
AddreplacedemblyPointerGroup("All replacedemblies", Allreplacedemblies);
}
19
View Source File : MainWindow.xaml.cs
License : MIT License
Project Creator : AgileoAutomation
License : MIT License
Project Creator : AgileoAutomation
private void open_Click(object sender, RoutedEventArgs e)
{
AllowDrop = false;
FolderBrowserDialog dialog = new FolderBrowserDialog();
if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
DirectoryInfo directory = new DirectoryInfo(dialog.SelectedPath);
if (directory.Exists
&& directory.GetFiles().Any(x => x.Extension == ".dll" || x.Extension == ".exe"))
{
SpecWindow = new SpecificationWindow();
SpecWindow.ShowDialog();
if (SpecWindow.OKClicked)
{
while (SpecWindow.OKClicked && !BuildAndDisplay(directory))
{
SpecWindow = new SpecificationWindow();
SpecWindow.ShowDialog();
}
}
}
else
System.Windows.MessageBox.Show("Invalid Directory");
}
AllowDrop = true;
}
19
View Source File : ContentsBrowser.cs
License : MIT License
Project Creator : alaabenfatma
License : MIT License
Project Creator : alaabenfatma
public void Load(string path, bool forced = false)
{
if (!Folder && !forced) return;
if (Parent.Container != null)
{
Parent.Path = path;
int x;
Parent.Container.Disable();
var d = new DirectoryInfo(path); //replaceduming Test is your Folder
var files = d.GetFiles(); //Getting Text files
var dirs = d.GetDirectories();
x = files.Length + dirs.Length;
Parent.Items.Clear();
if (x == 0)
{
Parent.Container.Enable();
Parent.Container.UpdateFoldersTree();
return;
}
foreach (var dirr in dirs)
Task.Factory.StartNew(() =>
{
Dispatcher.BeginInvoke(DispatcherPriority.Input,
new Action(() =>
{
if (Parent.Path == Directory.GetParent(dirr.FullName).FullName)
Parent.AddFolder(dirr.Name, dirr.Extension, dirr.FullName);
if (x == Parent.Items.Count)
{
Parent.Container.Enable();
Parent.Container.UpdateFoldersTree();
}
}));
});
foreach (var file in files)
Task.Factory.StartNew(() =>
{
Dispatcher.BeginInvoke(DispatcherPriority.Input,
new Action(() =>
{
if (Parent.Path == Directory.GetParent(file.FullName).FullName)
Parent.AddFile(file.Name, file.Extension, file.FullName);
if (x == Parent.Items.Count)
{
Parent.Container.Enable();
Parent.Container.UpdateFoldersTree();
}
}));
});
}
}
19
View Source File : BuildPostProcessor.cs
License : MIT License
Project Creator : aleab
License : MIT License
Project Creator : aleab
private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
{
// Get the subdirectories for the specified directory.
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
if (!dir.Exists)
throw new DirectoryNotFoundException("Source directory does not exist or could not be found: " + sourceDirName);
DirectoryInfo[] dirs = dir.GetDirectories();
// If the destination directory doesn't exist, create it.
if (!Directory.Exists(destDirName))
Directory.CreateDirectory(destDirName);
// Get the files in the directory and copy them to the new location.
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string temppath = Path.Combine(destDirName, file.Name);
file.CopyTo(temppath, false);
}
// If copying subdirectories, copy them and their contents to new location.
if (copySubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
string temppath = Path.Combine(destDirName, subdir.Name);
DirectoryCopy(subdir.FullName, temppath, copySubDirs);
}
}
}
19
View Source File : ExperimentController.cs
License : MIT License
Project Creator : AlexanderFroemmgen
License : MIT License
Project Creator : AlexanderFroemmgen
private void CreatePersistentSnapshotFolder(Experiment experiment)
{
// TODO: In case a file exists in the general and the specific framework folder, we get an exception.
var targetFolder = _directoryOptions.DataLocation + $"/Experiments/sim{experiment.Id:0000}";
var di = new DirectoryInfo(targetFolder);
if(di.Exists)
{
di.MoveTo(_directoryOptions.DataLocation + $"/Experiments/sim{experiment.Id:0000}_removed_at_{DateTime.Now:ddMMyy_Hmmss}");
di = new DirectoryInfo(targetFolder);
}
di.Create();
/* general experiment files */
var fileNameGeneral = _directoryOptions.DataLocation + "/ExperimentFramework";
foreach (var fileEntry in new DirectoryInfo(fileNameGeneral).GetFiles())
{
fileEntry.CopyTo(targetFolder + "/" + fileEntry.Name);
}
/* files for this experiment fileName */
var fileName = _directoryOptions.DataLocation + "/ExperimentTemplates/" + experiment.FileName + "/framework";
_directoryOptions.CopyDirectoryRecursively(new DirectoryInfo(fileName), targetFolder);
}
19
View Source File : ExperimentInstanceController.cs
License : MIT License
Project Creator : AlexanderFroemmgen
License : MIT License
Project Creator : AlexanderFroemmgen
private void copySnapshotFilesToArchive(ZipArchive archive)
{
var experimentFileName = _directoryOptions.DataLocation + $"/Experiments/sim{_currentExperimentInstance.ExperimentId:0000}";
var filesGeneral = new DirectoryInfo(experimentFileName).GetFiles();
foreach (var fileEntry in filesGeneral)
{
archive.CreateEntryFromFile(fileEntry.FullName, fileEntry.Name);
}
}
19
View Source File : DirectoryOptions.cs
License : MIT License
Project Creator : AlexanderFroemmgen
License : MIT License
Project Creator : AlexanderFroemmgen
public void CopyDirectoryRecursively(DirectoryInfo fromDi, string destPath)
{
new DirectoryInfo(destPath).Create();
foreach (var dirEntry in fromDi.GetDirectories())
{
var tmpDestPath = destPath + "/" + dirEntry.Name;
new DirectoryInfo(tmpDestPath).Create();
CopyDirectoryRecursively(dirEntry, tmpDestPath);
}
foreach (var dirEntry in fromDi.GetFiles())
{
dirEntry.CopyTo(destPath + "/" + dirEntry.Name);
}
}
19
View Source File : DirectoryOptions.cs
License : MIT License
Project Creator : AlexanderFroemmgen
License : MIT License
Project Creator : AlexanderFroemmgen
private void GetAllFilesRecursively(DirectoryInfo di, List<string> result, string prefix = "")
{
foreach (var dirEntry in di.GetFiles())
{
result.Add(prefix + dirEntry.Name);
}
foreach (var dirEntry in di.GetDirectories())
{
GetAllFilesRecursively(dirEntry, result, prefix + dirEntry.Name + "/");
}
}
19
View Source File : IconManager.cs
License : Apache License 2.0
Project Creator : Algoryx
License : Apache License 2.0
Project Creator : Algoryx
private void OnEnable()
{
m_iconNames.Clear();
IconManager.Directory = GetEditorData().String;
var di = new DirectoryInfo( IconManager.Directory );
if ( !di.Exists ) {
Debug.LogError( $"Icon directory doesn't exist: {IconManager.Directory}" );
return;
}
foreach ( var fi in di.GetFiles().OrderBy( fi => fi.Name ) )
if ( fi.Extension.ToLower() == ".png" )
m_iconNames.Add( Path.GetFileNameWithoutExtension( fi.Name ) );
GetEditorData( "NormalColorDark", entry => entry.Color = IconManager.NormalColorDark );
GetEditorData( "ActiveColorDark", entry => entry.Color = IconManager.ActiveColorDark );
GetEditorData( "DisabledColorDark", entry => entry.Color = IconManager.DisabledColorDark );
GetEditorData( "NormalColorLight", entry => entry.Color = IconManager.NormalColorLight );
GetEditorData( "ActiveColorLight", entry => entry.Color = IconManager.ActiveColorLight );
GetEditorData( "DisabledColorLight", entry => entry.Color = IconManager.DisabledColorLight );
}
19
View Source File : PathExtensions.cs
License : MIT License
Project Creator : aliakseiherman
License : MIT License
Project Creator : aliakseiherman
public static void Empty(this DirectoryInfo directory)
{
foreach (FileInfo file in directory.GetFiles()) file.Delete();
foreach (DirectoryInfo subDirectory in directory.GetDirectories()) subDirectory.Delete(true);
}
19
View Source File : BuildProcessCallbacksHandler.cs
License : Apache License 2.0
Project Creator : Algoryx
License : Apache License 2.0
Project Creator : Algoryx
public static void CopyDirectory( DirectoryInfo source, DirectoryInfo destination )
{
if ( !destination.Exists )
destination.Create();
foreach ( var fileInfo in source.GetFiles() )
fileInfo.CopyTo( Path.Combine( destination.FullName, fileInfo.Name ), true );
foreach ( var directoryInfo in source.GetDirectories() )
CopyDirectory( directoryInfo, new DirectoryInfo( Path.Combine( destination.FullName, directoryInfo.Name ) ) );
}
19
View Source File : Rename.cs
License : MIT License
Project Creator : Alkl58
License : MIT License
Project Creator : Alkl58
public static void RenameChunks(string currentPath)
{
//Create Array List with all Chunks
string[] chunks;
//Sets the Chunks directory
string sdira = currentPath + "\\Chunks";
//Add all Files in Chunks Folder to array
chunks = Directory.GetFiles(sdira, "*mkv", SearchOption.AllDirectories).Select(x => Path.GetFileName(x)).ToArray();
DirectoryInfo d = new DirectoryInfo(currentPath + "\\Chunks");
FileInfo[] infos = d.GetFiles();
int numberOfChunks = chunks.Count();
//outx.mkv = 8 | outxx.mkv = 9 (99) | outxxx.mkv = 10 (999) | outxxxx.mkv = 11 (9999) | outxxxxx.mkv = 12 (99999)
//int numberOfChunks = 20000;
if (numberOfChunks >= 10 && numberOfChunks <= 99)
{
foreach (FileInfo f in infos)
{
int count = f.ToString().Count();
if (count == 8)
{
File.Move(d + "\\" + f, d + "\\" + f.Name.Replace("out", "out0"));
}
}
}
else if (numberOfChunks >= 100 && numberOfChunks <= 999) //If you have more than 100 Chunks and less than 999
{
foreach (FileInfo f in infos)
{
int count = f.ToString().Count();
if (count == 8)
{
File.Move(d + "\\" + f, d + "\\" + f.Name.Replace("out", "out00"));
}
if (count == 9)
{
File.Move(d + "\\" + f, d + "\\" + f.Name.Replace("out", "out0"));
}
}
}
else if (numberOfChunks >= 1000 && numberOfChunks <= 9999) //If you have more than 1.000 Chunks and less than 9.999
{
foreach (FileInfo f in infos)
{
int count = f.ToString().Count();
if (count == 8)
{
File.Move(d + "\\" + f, d + "\\" + f.Name.Replace("out", "out000"));
}
if (count == 9)
{
File.Move(d + "\\" + f, d + "\\" + f.Name.Replace("out", "out00"));
}
if (count == 10)
{
File.Move(d + "\\" + f, d + "\\" + f.Name.Replace("out", "out0"));
}
}
}
else if (numberOfChunks >= 10000 && numberOfChunks <= 99999) //If you have more than 10.000 Chunks and less than 99.999
{
foreach (FileInfo f in infos)
{
int count = f.ToString().Count();
if (count == 8)
{
File.Move(d + "\\" + f, d + "\\" + f.Name.Replace("out", "out0000"));
}
if (count == 9)
{
File.Move(d + "\\" + f, d + "\\" + f.Name.Replace("out", "out000"));
}
if (count == 10)
{
File.Move(d + "\\" + f, d + "\\" + f.Name.Replace("out", "out00"));
}
if (count == 11)
{
File.Move(d + "\\" + f, d + "\\" + f.Name.Replace("out", "out0"));
}
}
}
else if (numberOfChunks >= 100000 && numberOfChunks <= 999999)
{
foreach (FileInfo f in infos)
{
int count = f.ToString().Count();
//If you have more than 100.000 Chunks and less than 999.999
//BTW are fu*** insane?
if (count == 8)
{
File.Move(d + "\\" + f, d + "\\" + f.Name.Replace("out", "out00000"));
}
if (count == 9)
{
File.Move(d + "\\" + f, d + "\\" + f.Name.Replace("out", "out0000"));
}
if (count == 10)
{
File.Move(d + "\\" + f, d + "\\" + f.Name.Replace("out", "out000"));
}
if (count == 11)
{
File.Move(d + "\\" + f, d + "\\" + f.Name.Replace("out", "out00"));
}
if (count == 12)
{
File.Move(d + "\\" + f, d + "\\" + f.Name.Replace("out", "out0"));
}
}
}
}
19
View Source File : FileSystemResultsWriter.cs
License : Apache License 2.0
Project Creator : allure-framework
License : Apache License 2.0
Project Creator : allure-framework
public void CleanUp()
{
using (var mutex = new Mutex(false, "729dc988-0e9c-49d0-9e50-17e0df3cd82b"))
{
mutex.WaitOne();
var directory = new DirectoryInfo(outputDirectory);
foreach (var file in directory.GetFiles()) file.Delete();
foreach (var dir in directory.GetDirectories()) dir.Delete(true);
mutex.ReleaseMutex();
}
}
See More Examples