GetDirectoryName() public static method

public static GetDirectoryName ( string path ) : string
path string
return string
    private void Search_OnClick(object sender, RoutedEventArgs e)
    {
        var ofd = new OpenFileDialog()
        {
            FileName         = "Select Folder.",
            InitialDirectory = PathTextBox.Text,
            ValidateNames    = false,
            CheckFileExists  = false,
            CheckPathExists  = false
        };

        if (ofd.ShowDialog(this) != true)
        {
            return;
        }
        PathTextBox !.Text = Path.GetDirectoryName(ofd.FileName) ?? "";
        PathTextBox.GetBindingExpression(TextBox.TextProperty)?.UpdateSource();
    }
示例#2
0
        public void InstallGenerateRequirementsTxt(PythonVisualStudioApp app) {
            using (var dis = InitPython3(app)) {
                var project = CreateTemporaryProject(app);

                var env = app.CreateProjectVirtualEnvironment(project, out string envName);
                env.Select();

                try {
                    app.ExecuteCommand("Python.InstallRequirementsTxt", "/y", timeout: 5000);
                    Assert.Fail("Command should not have executed");
                } catch (AggregateException ae) {
                    ae.Handle(ex => ex is COMException);
                } catch (COMException) {
                }

                var requirementsTxt = Path.Combine(Path.GetDirectoryName(project.FullName), "requirements.txt");
                File.WriteAllText(requirementsTxt, TestPackageSpec);

                app.ExecuteCommand("Python.InstallRequirementsTxt", "/y");

                app.SolutionExplorerTreeView.WaitForChildOfProject(
                    project,
                    TimeSpan.FromSeconds(30),
                    Strings.Environments,
                    envName,
                    TestPackageDisplay
                );

                File.Delete(requirementsTxt);

                app.ExecuteCommand("Python.GenerateRequirementsTxt", "/e:\"" + envName + "\"");

                app.SolutionExplorerTreeView.WaitForChildOfProject(
                    project,
                    "requirements.txt"
                );

                AssertUtil.ContainsAtLeast(
                    File.ReadAllLines(requirementsTxt).Select(s => s.Trim()),
                    TestPackageSpec
                );
            }
        }
示例#3
0
        private void ComboboxSelectedConfig_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (comboboxSelectedConfig.SelectedItem == null)
            {
                return;
            }

            if ((string)comboboxSelectedConfig.SelectedItem == "New Config")
            {
                ConfigEditorWindow configEditor = new(DataPath, null);
                configEditor.ShowDialog();

                if (configEditor.Cancel)
                {
                    comboboxSelectedConfig.SelectedItem = null;
                    return;
                }

                if (configEditor.ConfigName != null && configEditor.Config != null)
                {
                    ConfigToLoad = Path.Combine(DataPath, configEditor.ConfigName, "config.json");

                    if (!Directory.Exists(Path.GetDirectoryName(ConfigToLoad)))
                    {
                        Directory.CreateDirectory(Path.GetDirectoryName(ConfigToLoad));
                    }

                    File.WriteAllText(ConfigToLoad, JsonSerializer.Serialize(configEditor.Config, new() { AllowTrailingCommas = true, NumberHandling = JsonNumberHandling.AllowReadingFromString }));
                }
            }
            else
            {
                ConfigToLoad = Path.Combine(DataPath, (string)comboboxSelectedConfig.SelectedItem, "config.json");
            }

            Hide();

            MainWindow mainWindow = new(DataPath, ConfigToLoad);

            mainWindow.Show();

            Close();
        }
示例#4
0
 public void CreateIcon(string applicationName, string appPath)
 {
     try
     {
         object       shDesktop       = (object)"Desktop";
         WshShell     shell           = new WshShell();
         string       shortcutAddress = (string)shell.SpecialFolders.Item(ref shDesktop) + "\\" + applicationName + ".lnk";
         IWshShortcut shortcut        = (IWshShortcut)shell.CreateShortcut(shortcutAddress);
         shortcut.IconLocation     = appPath;
         shortcut.Description      = "EMSG Mobile";
         shortcut.WorkingDirectory = Path.GetDirectoryName(appPath);
         shortcut.TargetPath       = appPath;
         shortcut.Save();
     }
     catch (Exception)
     {
         //ToDo: Notify user?
     }
 }
示例#5
0
        private void CopyRemoteRunnerToServerIfNotExists()
        {
            //copy remote out

            var remotePath = _remotePhysicalPath;

            if (!Directory.Exists(remotePath))
            {
                Directory.CreateDirectory(remotePath);
            }

            var ewd = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "dropkick.remote");

            Logging.Fine("Copying remote execution files from '{0}' to '{1}'", ewd, remotePath);

            var local = Path.GetDirectoryName(ewd);

            if (local == null)
            {
                throw new Exception("Path to dk remote files should not be null");
            }

            var filesToCopy = Directory.GetFiles(ewd);

            foreach (var file in filesToCopy)
            {
                var dest = Path.Combine(remotePath, Path.GetFileName(file));
                var src  = Path.Combine(local, file);
                _fineLog.DebugFormat("[remote] '{0}'->'{1}'", src, dest);

                try
                {
                    //TODO: This should get smarter about whether the file is the same or not.
                    CopyFileWithNoLocking(src, dest);
                    //File.Copy(src, dest, true);
                }
                catch (IOException)
                {
                    _fineLog.DebugFormat("[remote][file] Error copying '{0}' to '{1}'", file, remotePath);
                    throw;
                }
            }
        }
示例#6
0
        public string[] GetAnalyzers()
        {
            var bridge = GetBridgeLocation();

            if (!string.IsNullOrEmpty(bridge))
            {
                var baseLocation     = IOPath.Combine(IOPath.GetDirectoryName(bridge), "..");
                var analyzerLocation = IOPath.GetFullPath(IOPath.Combine(baseLocation, "Analyzers"));

                if (Directory.Exists(analyzerLocation))
                {
                    return(Directory.GetFiles(analyzerLocation, "*Analyzers.dll", SearchOption.AllDirectories));
                }
            }

            // Local assets
            // return FileUtility.FindPackageAssetFullPath("Analyzers a:packages", ".Analyzers.dll");
            return(Array.Empty <string>());
        }
示例#7
0
        private void TransferFiles()
        {
            DateTime starttime  = DateTime.Now;
            long     totalbytes = 0;
            AsyncObservableCollection <FileItem> itemstoExport =
                new AsyncObservableCollection <FileItem>(Items.Where(x => x.IsChecked));

            dlg.MaxValue = itemstoExport.Count;
            dlg.Progress = 0;
            int          i       = 0;
            PhotoSession session = (PhotoSession)CameraDevice.AttachedPhotoSession ??
                                   ServiceProvider.Settings.DefaultSession;

            foreach (FileItem fileItem in itemstoExport)
            {
                dlg.Label       = fileItem.FileName;
                dlg.ImageSource = fileItem.Thumbnail;
                string fileName = Path.Combine(session.Folder, fileItem.FileName);
                if (File.Exists(fileName))
                {
                    fileName =
                        StaticHelper.GetUniqueFilename(
                            Path.GetDirectoryName(fileName) + "\\" + Path.GetFileNameWithoutExtension(fileName) + "_", 0,
                            Path.GetExtension(fileName));
                }
                CameraDevice.TransferFile(fileItem.DeviceObject.Handle, fileName);
                // double check if file was transferred
                if (File.Exists(fileName) && delete)
                {
                    CameraDevice.DeleteObject(fileItem.DeviceObject);
                }
                totalbytes += new FileInfo(fileName).Length;
                session.AddFile(fileName);
                i++;
                dlg.Progress = i;
            }
            dlg.Hide();
            double transfersec = (DateTime.Now - starttime).TotalSeconds;

            Log.Debug(string.Format(
                          "[BENCHMARK]Total byte transferred ;{0}\nTotal seconds :{1}\nSpeed : {2} Mbyte/sec ", totalbytes,
                          transfersec, (totalbytes / transfersec / 1024 / 1024).ToString("0000.00")));
        }
        public void GetFiles()
        {
            string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                                       "") + "\\res";

            LineReaded = 0;
            VnPath     = path;

            foreach (var drive in Directory.GetDirectories(path))
            {
                DirectoryInfo dir   = new DirectoryInfo(drive);
                FileInfo[]    Files = dir.GetFiles();

                if (Path.GetFileName(drive) == "Bg")
                {
                    foreach (var file in Files)
                    {
                        BgContent.Add(new fileData {
                            dir = Path.GetFileName(drive), path = file.FullName
                        });
                    }
                }
                else if (Path.GetFileName(drive) == "Sprite")
                {
                    foreach (var file in Files)
                    {
                        SpriteContent.Add(new fileData {
                            dir = Path.GetFileName(drive), path = file.FullName
                        });
                    }
                }
                else if (Path.GetFileName(drive) == "Music")
                {
                    foreach (var file in Files)
                    {
                        MusicContent.Add(new fileData {
                            dir = Path.GetFileName(drive), path = file.FullName
                        });
                    }
                }
            }
            LoadNovel();
        }
示例#9
0
        public GameWindow()
        {
            InitializeComponent();

            ClickSound     = new WMPLib.WindowsMediaPlayer();
            ClickSound.URL = $@"{Path.GetDirectoryName(Path.GetDirectoryName(Directory.GetCurrentDirectory()))}\Track List\Click.mp3";
            imagecount     = new List <Image>();
            timer          = new DispatcherTimer();
            timer.Tick    += new EventHandler(TimerTick);
            timer.Interval = new TimeSpan(0, 0, 0, 0, 800);
            timer.Start();
            timer2          = new DispatcherTimer();
            timer2.Tick    += new EventHandler(SpeedUpTimer);
            timer2.Interval = new TimeSpan(0, 0, 5);
            timer2.Start();
            Thread playmusic = new Thread(new ThreadStart(PlayMusic));

            playmusic.Start();
        }
        void InstallViaInner()
        {
            WriteLog("正在释放相关帮助程序...");
            var path    = Path.GetDirectoryName(_serviceInfo.ExePath);
            var log4Net = $"{path}\\log4net.dll";

            if (!File.Exists(log4Net))
            {
                File.WriteAllBytes(log4Net, Properties.Resources.log4net);
            }
            var app = $"{path}\\{_serviceInfo.ServiceName}.svr.exe";

            if (!File.Exists(app))
            {
                File.WriteAllBytes(app, Properties.Resources.ServiceApp);
            }
            var cfg = $"{app}.json";

            File.WriteAllText(cfg, JsonConvert.SerializeObject(new ExeServiceConfig()
            {
                Argument = _serviceInfo.Arguments,
                Exe      = _serviceInfo.ExePath
            }, Formatting.Indented));
            WriteLog("正在安装服务...");
            var depSvr = new string[_serviceInfo.DepService.Count];

            for (var i = 0; i < _serviceInfo.DepService.Count; i++)
            {
                depSvr[i] = _serviceInfo.DepService[i].Name;
            }

            ServiceHelper.Install(_serviceInfo.ServiceName,
                                  string.IsNullOrWhiteSpace(_serviceInfo.DisplayName)
                    ? _serviceInfo.ServiceName
                    : _serviceInfo.DisplayName,
                                  app,
                                  _serviceInfo.Desc,
                                  _serviceInfo.ServiceStartType,
                                  _serviceInfo.ServiceAccount,
                                  depSvr);
            WriteLog("安装成功,正在启动服务...");
            _cmdProcess.StandardInput.WriteLine($"net start {_serviceInfo.ServiceName}");
        }
示例#11
0
        private static IEnumerable <string> GetProjectPackageReferences(string csproj)
        {
            var project           = XElement.Load(csproj);
            var packageReferences = project
                                    .Descendants("PackageReference")
                                    .Select(e => e.Attribute("Include")?.Value);

            var csprojdirectory = IOPath.GetDirectoryName(csproj);
            var imports         = project
                                  .Descendants("Import")
                                  .Select(e => IOPath.Combine(csprojdirectory, e.Attribute("Project").Value));

            foreach (var import in imports)
            {
                packageReferences = packageReferences.Concat(GetProjectPackageReferences(import));
            }

            return(packageReferences);
        }
示例#12
0
    static void Main(string[] args)
    {
        string appPath    = System.Reflection.Assembly.GetExecutingAssembly().Location;
        string appDir     = Path.GetDirectoryName(appPath);
        string scriptPath = Path.Combine(appDir, SCRIPT);

        ProcessStartInfo psInfo = new ProcessStartInfo();

        psInfo.FileName  = RUBY;
        psInfo.Arguments = scriptPath + " " + String.Join(" ", args);
        //psInfo.Arguments = scriptPath;
        //psInfo.CreateNoWindow = true;
        psInfo.CreateNoWindow  = false;
        psInfo.UseShellExecute = false;

        log(scriptPath);
        log(psInfo.Arguments);
        Process.Start(psInfo);
    }
        /// <summary>
        /// Gets the set of search paths for the specified factory as
        /// efficiently as possible. This may involve executing the
        /// interpreter, and may cache the paths for retrieval later.
        /// </summary>
        public static async Task <IList <PythonLibraryPath> > GetDatabaseSearchPathsAsync(InterpreterConfiguration config, string cachePath)
        {
            for (int retries = 5; retries > 0; --retries)
            {
                List <PythonLibraryPath> paths;
                if (!string.IsNullOrEmpty(cachePath))
                {
                    paths = GetCachedDatabaseSearchPaths(cachePath);
                    if (paths != null)
                    {
                        return(paths);
                    }
                }

                try {
                    paths = await GetUncachedDatabaseSearchPathsAsync(config.InterpreterPath).ConfigureAwait(false);

                    if (!string.IsNullOrEmpty(cachePath))
                    {
                        WriteDatabaseSearchPaths(cachePath, paths);
                    }
                    return(paths);
                } catch (InvalidOperationException) {
                    // Failed to get paths
                    break;
                } catch (UnauthorizedAccessException) {
                    // Failed to write paths - sleep and then loop
                    Thread.Sleep(50);
                } catch (IOException) {
                    // Failed to write paths - sleep and then loop
                    Thread.Sleep(50);
                }
            }

            var ospy = PathUtils.FindFile(config.PrefixPath, "os.py", firstCheck: new[] { "Lib" });

            if (!string.IsNullOrEmpty(ospy))
            {
                return(GetDefaultDatabaseSearchPaths(IOPath.GetDirectoryName(ospy)));
            }

            return(Array.Empty <PythonLibraryPath>());
        }
示例#14
0
        private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
        {
            var settings = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            SaveFileDialog saveFileDialog = new SaveFileDialog
            {
                FileName         = Path.GetFileName(ConfigurationManager.AppSettings["path"]),
                Filter           = "Excel (*.xlsx)|*.xlsx",
                InitialDirectory = Path.GetDirectoryName(ConfigurationManager.AppSettings["path"])
            };

            if (saveFileDialog.ShowDialog() == true)
            {
                (DataContext as MainViewModel).Path = saveFileDialog.FileName;

                settings.AppSettings.Settings.Add("path", saveFileDialog.FileName);
                settings.Save(ConfigurationSaveMode.Modified);
            }
        }
示例#15
0
 /// <summary>
 ///     Copies a file.
 /// </summary>
 /// <param name="file">File object to copy</param>
 /// <param name="destinationPath">String representation of destination file path</param>
 /// <param name="overwrite">Toggle to overwrite existing files</param>
 /// <returns name="bool">Node performs a task, return true of copy action succeed.</returns>
 public static bool CopyFile(FileInfo file, string destinationPath, bool overwrite = false)
 {
     try
     {
         if (Path.GetDirectoryName(destinationPath) != string.Empty && FileExtension(destinationPath) != string.Empty)
         {
             file.CopyTo(destinationPath, overwrite);
         }
         else
         {
             throw new FileNotFoundException(Properties.Resources.InvalidDestinationPathErrorMessage, destinationPath);
         }
     }
     catch (System.Exception ex)
     {
         throw ex;
     }
     return(true);
 }
示例#16
0
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            ObservableCollection <TableItem> _playList = new ObservableCollection <TableItem>();
            List <string> lines = new List <string>();

            OpenFileDialog ofd = new OpenFileDialog();

            ofd.Title  = "Load CSV";
            ofd.Filter = "CSV file|*.csv";

            ofd.InitialDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            bool?result = ofd.ShowDialog();

            if (result.HasValue && result.Value)
            {
                Cursor = Cursors.Wait;


                using (StreamReader sr = new StreamReader(ofd.FileName))
                {
                    while (sr.Peek() >= 0)
                    {
                        lines.Add(sr.ReadLine());
                    }
                }

                int i = 1;
                foreach (string rows in lines)
                {
                    if (i != 1)
                    {
                        TableItem song = new TableItem(rows.Split(',')[0], rows.Split(',')[1], rows.Split(',')[2], rows.Split(',')[3]);
                        _playList.Add(song);
                    }
                    i++;
                }

                LoadCSV win = new LoadCSV(_playList, ofd.SafeFileName);
                win.ShowDialog();

                Cursor = Cursors.Arrow;
            }
        }
示例#17
0
        private void FilePathBox_OnPopulating(AutoCompleteBox box, string allowed_ext, object sender, PopulatingEventArgs e)
        {
            string text    = box.Text;
            string dirname = Path.GetDirectoryName(text);

            if (Directory.Exists(text) && !text.EndsWith("\\."))
            {
                dirname = text;
            }
            var candidates = new List <string>();

            if (!String.IsNullOrWhiteSpace(dirname))
            {
                try {
                    if (Directory.Exists(dirname) || Directory.Exists(Path.GetDirectoryName(dirname)))
                    {
                        string[] dirs = Directory.GetDirectories(dirname, "*.*", SearchOption.TopDirectoryOnly);


                        Array.ForEach(new[] { dirs }, (x) =>
                                      Array.ForEach(x, (y) => {
                            if (y.StartsWith(dirname, StringComparison.CurrentCultureIgnoreCase))
                            {
                                candidates.Add(y);
                            }
                        }));
                        if (!String.IsNullOrWhiteSpace(allowed_ext))
                        {
                            var files = Directory.GetFiles(dirname, "*." + allowed_ext, SearchOption.TopDirectoryOnly);
                            Array.ForEach(new[] { files }, (x) =>
                                          Array.ForEach(x, (y) => {
                                if (y.StartsWith(dirname, StringComparison.CurrentCultureIgnoreCase))
                                {
                                    candidates.Add(y);
                                }
                            }));
                        }
                    }
                } catch (Exception) { }
            }
            box.ItemsSource = candidates;
            box.PopulateComplete();
        }
示例#18
0
        private void SaveFontFile(string path)
        {
            var resourceName =
                _iconFontDescriptor.GetType()
                .Assembly.GetManifestResourceNames()
                .FirstOrDefault(x => x.EndsWith(_iconFontDescriptor.FontFileName));

            if (resourceName == null)
            {
                throw new ArgumentOutOfRangeException("No such font in resources: " + _iconFontDescriptor.FontFileName);
            }
            Directory.CreateDirectory(Path.GetDirectoryName(path));
            using (var file = File.Create(path))
                using (var resource = _iconFontDescriptor.GetType().Assembly.GetManifestResourceStream(resourceName))
                {
                    resource.CopyTo(file);
                    file.Flush();
                }
        }
示例#19
0
        private Uri CreateTempFile()
        {
            string path = _temporaryFilePath;

            if (File.Exists(path))
            {
                File.Delete(path);
            }

            string dirPath = Path.GetDirectoryName(path);

            if (dirPath != null && !Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }

            using (var tempFile = new Java.IO.File(path))
                return(Uri.FromFile(tempFile));
        }
示例#20
0
        private List <MyPlaylist> LoadPlaylist()
        {
            List <MyPlaylist> plejliste = new List <MyPlaylist>();
            string            path1     = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            string text = File.ReadAllText(Path.Combine(path1, MainWindow.Email + "Playlists.txt"));

            string[] plist = text.Split(new string[] { "PLAYLIST " }, StringSplitOptions.None);

            foreach (string lists in plist)
            {
                if (lists != "")
                {
                    MyPlaylist mpl = new MyPlaylist();
                    int        selected;
                    string[]   items = lists.Split(new string[] { "*#" }, StringSplitOptions.None);
                    Int32.TryParse(items[0], out selected);
                    mpl.SelectedId = selected;
                    mpl.Title      = items[1];
                    mpl.Url        = items[2].Split('\n')[0].Split('\r')[0];

                    string[] tracks = items[2].Split(new string[] { "\r\n\r\n" }, StringSplitOptions.None);
                    string[] tr     = tracks[1].Split(new string[] { "\r\n" }, StringSplitOptions.None);

                    foreach (string track in tr)
                    {
                        if (track != "")
                        {
                            string[] song_stuff = track.Split(new string[] { "|?" }, StringSplitOptions.None);
                            int      selectedtr;
                            Int32.TryParse(song_stuff[0].Split(' ')[1], out selectedtr);
                            Song song = new Song(song_stuff[2], song_stuff[3], song_stuff[1], song_stuff[4], selectedtr);
                            mpl.NumOfSongs = tr.Count() - 1;
                            mpl.Songs.Add(song);
                        }
                    }
                    plejliste.Add(mpl);
                }
            }

            return(plejliste);
        }
示例#21
0
        private void ImportFile(string path)
        {
            _selectedFile     = path;
            _selectedFileInfo = new FileInfo(_selectedFile);

            var    length = _selectedFileInfo.Length;
            double adaptedLength;
            string unit;

            if (length < 1024)
            {
                adaptedLength = length;
                unit          = "B";
            }
            else if (length < 1048576)
            {
                adaptedLength = length / 1024d;
                unit          = "KiB";
            }
            else if (length < 1073741824)
            {
                adaptedLength = length / 1048576d;
                unit          = "MiB";
            }
            else
            {
                adaptedLength = length / 1073741824d;
                unit          = "GiB";
            }

            adaptedLength = Math.Round(adaptedLength, 2);
            _lengthInMiB  = Math.Round(length / 1048576d, 2).ToString(CultureInfo.InvariantCulture);

            TblSelectedFile.Text =
                $"{Path.GetFileName(_selectedFile)} ({adaptedLength} {unit})";
            ImgSelectedFile.Source = Util.GetIconByFilename(_selectedFile).ToImageSource();

            TbFileDestination.Text =
                $"{Path.GetDirectoryName(_selectedFile)}\\{Path.GetFileNameWithoutExtension(_selectedFile)}_{(RbEncrypt.IsChecked == true ? "Encrypted" : "Decrypted")}{Path.GetExtension(_selectedFile)}";

            CheckFields();
        }
示例#22
0
        public void InstallGenerateRequirementsTxt()
        {
            using (var app = new PythonVisualStudioApp())
                using (var dis = Init(app)) {
                    var project = CreateTemporaryProject(app);

                    string envName;
                    var    env = app.CreateVirtualEnvironment(project, out envName);
                    env.Select();

                    try {
                        app.ExecuteCommand("Python.InstallRequirementsTxt", "/y", timeout: 5000);
                        Assert.Fail("Command should not have executed");
                    } catch (AggregateException ae) {
                        ae.Handle(ex => ex is COMException);
                    } catch (COMException) {
                    }

                    var requirementsTxt = Path.Combine(Path.GetDirectoryName(project.FullName), "requirements.txt");
                    File.WriteAllText(requirementsTxt, "azure==0.6.2");

                    app.ExecuteCommand("Python.InstallRequirementsTxt", "/y");

                    app.SolutionExplorerTreeView.WaitForChildOfProject(
                        project,
                        SR.GetString(SR.Environments),
                        envName,
                        "azure (0.6.2)"
                        );

                    File.Delete(requirementsTxt);

                    app.ExecuteCommand("Python.GenerateRequirementsTxt", "/e:\"" + envName + "\"");

                    app.SolutionExplorerTreeView.WaitForChildOfProject(
                        project,
                        "requirements.txt"
                        );

                    Assert.AreEqual("azure==0.6.2", File.ReadAllText(requirementsTxt).Trim());
                }
        }
示例#23
0
        //------------------------------------------------------------------------------
        // buildLoadInfo
        //
        // Extract the map description from the .mis file
        //------------------------------------------------------------------------------

        public static void BuildLoadInfo(string mission)
        {
            //Replaced the torque file stuff w/ csharp, less stuff inside of torque.
            ClearLoadInfo();
            string missionpath = Path.GetDirectoryName(Directory.GetCurrentDirectory()) + "\\" + mission.Replace("/", "\\");

            if (File.Exists(missionpath))
            {
                string infoObject = "";
                using (StreamReader sr = new StreamReader(missionpath))
                {
                    bool inInfoBlock = false;
                    while (sr.Peek() >= 0)
                    {
                        string line = sr.ReadLine();
                        if (line.Trim().StartsWith("new ScriptObject(MissionInfo) {"))
                        {
                            inInfoBlock = true;
                        }
                        if (line.Trim().StartsWith("new LevelInfo(theLevelInfo) {"))
                        {
                            inInfoBlock = true;
                        }
                        else if (inInfoBlock && line.Trim().StartsWith("};"))
                        {
                            inInfoBlock = false;
                            infoObject += line;
                            break;
                        }
                        if (inInfoBlock)
                        {
                            infoObject += line + " ";
                        }
                    }
                }
                omni.console.Eval(infoObject);
            }
            else
            {
                omni.console.error(string.Format("Level File {0} not found.", mission));
            }
        }
示例#24
0
        public void GetFileName()
        {
            string apkfile = $"{Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)}\\AppDatas\\";

            if (!Directory.Exists(apkfile))
            {
                Directory.CreateDirectory(apkfile);
            }

            var    files       = Directory.GetFiles(apkfile, "*.apk");
            int    decId       = 0;
            int    Heightapp   = 0;
            int    Len2        = 0;
            double WidthappLen = 50;

            foreach (var fullPath in files)
            {
                string filename = System.IO.Path.GetFileName(fullPath);//文件名

                Button btn = new Button
                {
                    Name                = "Button" + decId++,
                    Content             = filename,                                                 //按钮标题
                    Height              = 40,                                                       //按钮高度
                    Width               = (this.Width - 100) / 4,                                   //按钮宽度
                    HorizontalAlignment = HorizontalAlignment.Left,
                    Margin              = new Thickness(WidthappLen + Len2++ *10, Heightapp, 0, 0), //在界面上按钮的位置
                    VerticalAlignment   = VerticalAlignment.Top,
                    Visibility          = Visibility.Visible
                };
                WidthappLen += btn.Width; //下一个按钮递增的距离
                if (decId % 4 == 0)       //每行4个按钮
                {
                    Heightapp  += 100;    //每行按钮之间的高度
                    WidthappLen = 50;     //每行按钮第一个按钮离左边窗口的距离
                    Len2        = 0;      //下一个按钮递增的距离
                }

                btn.Click += new RoutedEventHandler(btnInstall_Click);
                applist.Children.Add(btn);
            }
        }
示例#25
0
        public void DeferredSaveWithDot()
        {
            string fullname;

            using (var app = new PythonVisualStudioApp()) {
                // http://pytools.codeplex.com/workitem/623
                // enable deferred saving on projects
                var props     = app.Dte.get_Properties("Environment", "ProjectsAndSolution");
                var prevValue = props.Item("SaveNewProjects").Value;
                props.Item("SaveNewProjects").Value = false;
                app.OnDispose(() => { props.Item("SaveNewProjects").Value = prevValue; });


                using (var newProjDialog = app.FileNewProject()) {
                    newProjDialog.FocusLanguageNode();

                    var consoleApp = newProjDialog.ProjectTypes.FindItem("Python Application");
                    consoleApp.Select();
                    newProjDialog.ProjectName = "Fob.Oar";
                    newProjDialog.OK();
                }

                // wait for new solution to load...
                for (int i = 0; i < 100 && app.Dte.Solution.Projects.Count == 0; i++)
                {
                    System.Threading.Thread.Sleep(1000);
                }

                using (var saveDialog = AutomationDialog.FromDte(app, "File.SaveAll")) {
                    saveDialog.ClickButtonAndClose("Save");
                }

                fullname = app.Dte.Solution.FullName;
            }

            try {
                // Delete the created directory after the solution has been
                // closed.
                Directory.Delete(Path.GetDirectoryName(fullname), true);
            } catch {
            }
        }
示例#26
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Logger.Event("Install");
                Error.Visibility = Visibility.Hidden;
                var    installationPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                string cmd = Path.Combine(installationPath, "Dependencies\\install.ps1");

                var gitInstallPath = GitHelper.GetGitInstallationPath();

                var proc = new Process
                {
                    StartInfo = new ProcessStartInfo
                    {
                        FileName         = "powershell.exe",
                        WorkingDirectory = Path.Combine(installationPath, "Dependencies"),
                        UseShellExecute  = true,
                        Arguments        = String.Format("-ExecutionPolicy ByPass -NoLogo -NoProfile -File \"" + cmd + "\" \"{0}\"", gitInstallPath),
                        Verb             = "runas",
                        LoadUserProfile  = false
                    }
                };
                proc.Start();
                proc.WaitForExit();

                if (proc.ExitCode != 0)
                {
                    Error.Text       = Error.Text.Replace("{0}", proc.ExitCode.ToString());
                    Error.Visibility = Visibility.Visible;
                }
                else
                {
                    parent.Refresh();
                }
            }
            catch (Exception ex)
            {
                parent.ShowNotification(ex.ToString(), NotificationType.Error);
                Logger.Exception(ex);
            }
        }
示例#27
0
        /// <summary>
        /// Universal data managment
        /// </summary>
        /// <param name="path">The path to the data file</param>
        public UniversalData(string path, EDataType DefaultDataType = EDataType.JSON)
        {
            this.Path       = path + ".dat";      // Set the path
            this.CreatedNew = !File.Exists(Path); // Check if the file has to be created

            if (!Directory.Exists(PT.GetDirectoryName(Path)))
            {
                Directory.CreateDirectory(PT.GetDirectoryName(Path));
            }
            if (CreatedNew)
            {
                DataType = DefaultDataType; // Set the data type

                switch (DefaultDataType)
                {
                case EDataType.JSON:
                    JSON = new JsonData(Path);     // Create the JSON file
                    break;

                case EDataType.XML:
                    XML = new XMLData(Path);     // Create the XML file
                    break;
                }

                return; // No need to continue
            }

            if (XMLData.CheckFile(Path))
            {
                DataType = EDataType.XML; // An XML file
                XML      = new XMLData(Path);
            }
            else if (JsonData.CheckFile(Path))
            {
                DataType = EDataType.JSON; // A JSON file
                JSON     = new JsonData(Path);
            }
            else
            {
                DataType = EDataType.UNKNOWN; // Unknown type/corrupted file
            }
        }
示例#28
0
 private void EditorClosing(object sender, FormClosingEventArgs e)
 {
     foreach (var doc in DocumentManager.Documents.ToArray())
     {
         if (!PromptForChanges(doc))
         {
             e.Cancel = true;
             return;
         }
     }
     SidebarManager.SaveLayout();
     ViewportManager.SaveLayout();
     SettingsManager.SaveSession(DocumentManager.Documents.Select(x => Tuple.Create(x.MapFile, x.Game)));
     SettingsManager.Write();
     if (_updateExecutable != null && File.Exists(_updateExecutable))
     {
         var loc = Path.GetDirectoryName(typeof(Editor).Assembly.Location);
         Process.Start(_updateExecutable, "/S" + (loc != null ? " /D=" + loc : ""));
     }
 }
示例#29
0
        private string getSceneAssetPrefix()
        {
            Scene  scene = EditorSceneManager.GetActiveScene();
            string path  = scene.path;

            string directoryPath;
            string fileName;

            if (File.Exists(path) == false)
            {
                directoryPath = Application.dataPath + "/Temp";
                fileName      = "Temp";
            }
            else
            {
                directoryPath = Path.GetDirectoryName(path);
                fileName      = Path.GetFileNameWithoutExtension(path);
            }
            return(directoryPath + "/" + fileName);
        }
        private void OnBrowseExe(object sender, RoutedEventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();

            dialog.Title           = "Choose a Terraria Executable";
            dialog.FileName        = textBoxExe.Text;
            dialog.Filter          = "Executable Files|*.exe|All Files|*.*";
            dialog.FilterIndex     = 0;
            dialog.CheckFileExists = true;
            try {
                dialog.InitialDirectory = Path.GetDirectoryName(textBoxExe.Text);
            }
            catch { }
            var result = dialog.ShowDialog(this);

            if (result.HasValue && result.Value)
            {
                textBoxExe.Text = dialog.FileName;
            }
        }