コード例 #1
0
ファイル: FluentPathSteps.cs プロジェクト: bleroy/FluentPath
 public void GivenACleanDirectory()
 {
     // foo.txt
     // bar/
     //   baz.txt
     //   notes.txt
     //   bar/
     //     deep.txt
     // sub/
     //   baz.txt
     //   binary.bin
     //   subsub/
     _path = new Path(SystemIO.Path.GetTempPath())
         .CreateSubDirectory("FluentPathSpecs")
         .MakeCurrent();
     _path
         .FileSystemEntries()
         .Delete(true);
     _path.CreateFile("foo.txt", "This is a text file named foo.");
     var bar = _path.CreateSubDirectory("bar");
     bar.CreateFile("baz.txt", "bar baz")
        .LastWriteTime(DateTime.Now.AddSeconds(-2));
     bar.CreateFile("notes.txt", "This is a text file containing notes.");
     var barbar = bar.CreateSubDirectory("bar");
     barbar.CreateFile("deep.txt", "Deep thoughts");
     var sub = _path.CreateSubDirectory("sub");
     sub.CreateSubDirectory("subsub");
     sub.CreateFile("baz.txt", "sub baz")
        .LastWriteTime(DateTime.Now);
     sub.CreateFile("binary.bin",
         new byte[] {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0xFF});
 }
コード例 #2
0
ファイル: PathStorage.cs プロジェクト: cwetanow/Telerik
        public static void SavePath(Path path, string fileName)
        {
            var writer = new StreamWriter(fileName + ".txt");

            writer.WriteLine(path.ToString());
            writer.Close();
        }
コード例 #3
0
		public async Task Icon ()
		{
			var size = new Size (64);
			var canvas = Platforms.Current.CreateImageCanvas (size, scale: 2);
			canvas.SaveState ();
			canvas.Scale (size);
			canvas.Translate (1 / 8.0, 0);

			var p = new Path ();
			p.MoveTo (0, 1);
			p.LineTo (0, 0);
			p.LineTo (0.5, 1);
			p.LineTo (0.5, 0);

			var colors = new [] {
				"#DCDCDD",
				"#C5C3C6",
				"#46494C",
				"#4C5C68",
				"#68A5E2",
			};
			foreach (var c in colors) {
				p.Pen = new Pen (c, 1 / 4.0);
				p.Draw (canvas);
				canvas.Translate (1 / 16.0, 0);
			}

			await SaveImage (canvas, "Icon.png");
		}
コード例 #4
0
        public static Path Load(string filePath)
        {
            Path path = new Path();
            try
            {
                using (StreamReader file = new StreamReader(filePath))
                {
                    string line;
                    while((line = file.ReadLine()) != String.Empty && line != null)
                    {
                        try
                        {
                            double[] coords = Array.ConvertAll<string, double>(line.Substring(line.IndexOf("{") + 1).Split(new char[]{';','}'}, StringSplitOptions.RemoveEmptyEntries), double.Parse);
                            Point3D point = new Point3D(coords[0], coords[1], coords[2]);
                            path.AddPoint(point);
                        }
                        catch
                        {
                            throw new FormatException(String.Format("Invalid format of coordinates in the file {0}", filePath));
                        }

                    }
                }
            }
            catch(FileNotFoundException)
            {
                throw new FileNotFoundException("File {0} not found", filePath);
            }
            return path;
        }
コード例 #5
0
		public IDisposable RegisterNotification(Path path, string filter = "*", bool includeSubdirectories = false,
		                                        Action<IFile> created = null, Action<IFile> modified = null,
		                                        Action<IFile> deleted = null, Action<IFile> renamed = null)
		{
			if (created == null && modified == null && renamed == null && deleted == null)
				throw new ArgumentException("One event type (created, modified, renamed or deleted) must be specified.");

			WatcherChangeTypes watcher = 0;
			if (created != null) watcher |= WatcherChangeTypes.Created;
			if (modified != null) watcher |= WatcherChangeTypes.Changed;
			if (renamed != null) watcher |= WatcherChangeTypes.Renamed;
			if (deleted != null) watcher |= WatcherChangeTypes.Deleted;


			var id = new FileSystemNotificationIdentifier(path ?? new Path(Environment.CurrentDirectory), watcher, filter ?? "*",
			                                              includeSubdirectories);
			IFileSytemNotifierEntry entry = null;

			if (!Watchers.TryGetValue(id, out entry))
			{
				lock (Watchers)
				{
					if (!Watchers.TryGetValue(id, out entry))
						Watchers.Add(id, entry = CreateEntry(id));
				}
			}
			return entry.AddNotifiers(created, deleted, modified, renamed);
		}
コード例 #6
0
ファイル: InMemoryFile.cs プロジェクト: bittercoder/Windsor
		public InMemoryFile(string filePath)
		{
			Path = new Path(filePath);
			Name = Path.GetFileName(filePath);
			NameWithoutExtension = Path.GetFileNameWithoutExtension(filePath);

			_LastModifiedTimeUtc = null;
		}
コード例 #7
0
ファイル: PathTests.cs プロジェクト: michaelstonis/NGraphics
		public void TurtleGraphics ()
		{
			var p = new Path ();
			p.MoveTo (new Point (100, 200));
			p.LineTo (new Point (200, 250));
			p.LineTo (new Point (100, 300));
			p.Close ();
		}
コード例 #8
0
 /// <summary>
 /// 	Creates the specified directory.
 /// </summary>
 /// <param name = "path">
 /// 	A <see cref = "string" /> containing the path of the directory to create.
 /// </param>
 /// <exception cref = "ArgumentNullException">
 /// 	<paramref name = "path" /> is <see langword = "null" />.
 /// </exception>
 /// <exception cref = "ArgumentException">
 /// 	<paramref name = "path" /> is an empty string (""), contains only white 
 /// 	space, or contains one or more invalid characters as defined in 
 /// 	<see cref = "System.IO.Path.GetInvalidPathChars()" />.
 /// 	<para>
 /// 		-or-
 /// 	</para>
 /// 	<paramref name = "path" /> contains one or more components that exceed
 /// 	the drive-defined maximum length. For example, on Windows-based 
 /// 	platforms, components must not exceed 255 characters.
 /// </exception>
 /// <exception cref = "PathTooLongException">
 /// 	<paramref name = "path" /> exceeds the system-defined maximum length. 
 /// 	For example, on Windows-based platforms, paths must not exceed 
 /// 	32,000 characters.
 /// </exception>
 /// <exception cref = "DirectoryNotFoundException">
 /// 	<paramref name = "path" /> contains one or more directories that could not be
 /// 	found.
 /// </exception>
 /// <exception cref = "UnauthorizedAccessException">
 /// 	The caller does not have the required access permissions.
 /// </exception>
 /// <exception cref = "IOException">
 /// 	<paramref name = "path" /> is a file.
 /// 	<para>
 /// 		-or-
 /// 	</para>
 /// 	<paramref name = "path" /> specifies a device that is not ready.
 /// </exception>
 /// <remarks>
 /// 	Note: Unlike <see cref = "System.IO.Directory.CreateDirectory(System.String)" />, this method only creates 
 /// 	the last directory in <paramref name = "path" />.
 /// </remarks>
 public static void Create(Path path)
 {
     if (!NativeMethods.CreateDirectory(path.LongFullPath, IntPtr.Zero))
     {
         // To mimic Directory.CreateDirectory, we don't throw if the directory (not a file) already exists
         var errorCode = Marshal.GetLastWin32Error();
         if (errorCode != NativeMethods.ERROR_ALREADY_EXISTS || !Exists(path))
             throw LongPathCommon.GetExceptionFromWin32Error(errorCode);
     }
 }
コード例 #9
0
ファイル: Output.cs プロジェクト: KAW0/Alter-Native
        public Output()
        {
			this.path = new Path();
            this.adc = new StreamWriter(this.path.GetPath() + @"/adc.txt", true);
            //this.gpsUtm = new StreamWriter(this.path.GetPath() + @"/gpsUtm.txt", true);
            this.imuEuler = new StreamWriter(this.path.GetPath() + @"/imuEuler.txt", true);
            //this.imuRaw = new StreamWriter(this.path.GetPath() + @"/imuRaw.txt", true);
            //this.gpsGeo = new StreamWriter(this.path.GetPath() + @"/gpsGeo.txt", true);
			this.pwm = new StreamWriter(this.path.GetPath() + @"/pwm.txt", true);
        }
コード例 #10
0
 public static void SavePath(Path path, string filePath)
 {
     using (var writer = new StreamWriter(filePath))
     {
         foreach (var point in path)
         {
             writer.WriteLine(point);
         }
     }
 }
コード例 #11
0
 // writes path to file
 public static void Write(Path source, string filename)
 {
     using (StreamWriter sw = new StreamWriter(filename)) // if something goes wrong, a standard exception procedure will take place
     {
         sw.WriteLine(source.Count); // writes number of points of the path
         foreach (Point3D item in source)
         {
             sw.WriteLine("{0} {1} {2}", item.X, item.Y, item.Z); // writes each point into the path on a separate line
         }
     }
 }
コード例 #12
0
ファイル: FileSystem.cs プロジェクト: bspell1/SkyFloe
 /// <summary>
 /// Creates a new file or opens an existing file for reading/writing
 /// Seeks to the end of the file
 /// </summary>
 /// <param name="path">
 /// Path to the file to append
 /// </param>
 /// <returns>
 /// A stream for the new file
 /// </returns>
 public static Stream Append(Path path)
 {
     Directory.CreateDirectory(path.Parent);
      var stream = new FileStream(
     path,
     FileMode.OpenOrCreate,
     FileAccess.ReadWrite,
     FileShare.Read
      );
      stream.Seek(0, SeekOrigin.End);
      return stream;
 }
コード例 #13
0
ファイル: PathTests.cs プロジェクト: michaelstonis/NGraphics
		public void Contains ()
		{
			var p = new Path ();
			p.MoveTo (new Point (0, 0));
			p.LineTo (new Point (100, 0));
			p.LineTo (new Point (100, 50));
			p.Close ();

			Assert.IsFalse (p.Contains (new Point (0, 1)));
			Assert.IsTrue (p.Contains (new Point (0, 0)));
			Assert.IsTrue (p.Contains (new Point (99, 49)));
			Assert.IsFalse (p.Contains (new Point (50, 49)));
		}
コード例 #14
0
ファイル: PathStorage.cs プロジェクト: rsmont/OOP
 public static void SavePath(Path path, string filePath)
 {
     using (var writer = new StreamWriter(filePath))
     {
         foreach (var points in path.Paths)
         {
             StringBuilder sb = new StringBuilder();
             sb.Append(points.PointX + "," + points.PointY + "," + points.PointZ);
             writer.Write(sb);
             writer.WriteLine();
         }
     }
 }
コード例 #15
0
 public static Path LoadPathFromFile(string file)
 {
     Path path3D = new Path();
     string[] pointsFromText = File.ReadAllText(file).Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
     
     for (int i = 0; i < pointsFromText.Length; i++)
     {
         string[] coordinates = pointsFromText[i].Split(Separators, StringSplitOptions.RemoveEmptyEntries).ToArray();
         
         path3D.AddPoint(new Point3D( double.Parse(coordinates[1]), double.Parse(coordinates[3]), double.Parse(coordinates[5])));
     }
         
     return path3D;
 }
コード例 #16
0
 // Before
 public void openFileSystem()
 {
     conf = new JobConf();
     // all columns
     conf.set("columns", "userid,string1,subtype,decimal1,ts");
     conf.set("columns.types", "bigint,string,double,decimal,timestamp");
     // needed columns
     conf.set(ColumnProjectionUtils.READ_ALL_COLUMNS, "false");
     conf.set(ColumnProjectionUtils.READ_COLUMN_IDS_CONF_STR, "0,2");
     conf.set(ColumnProjectionUtils.READ_COLUMN_NAMES_CONF_STR, "userid,subtype");
     fs = FileSystem.getLocal(conf);
     testFilePath = new Path(workDir, "TestOrcFile." +
         testCaseName.getMethodName() + ".orc");
     fs.delete(testFilePath, false);
 }
コード例 #17
0
ファイル: PathStorage.cs プロジェクト: cwetanow/Telerik
        public static Path LoadPath(string fileName)
        {
            var reader = new StreamReader(fileName + ".txt");
            var temp = reader.ReadToEnd();
            reader.Close();
            var points = temp.Split(new char[] { '[', ']', ';', ' ' }, StringSplitOptions.RemoveEmptyEntries);
            var newPath = new Path();
            for (int i = 0; i < points.Length - 1; i += 3)
            {
                var temporary = new Point(double.Parse(points[i]), double.Parse(points[i + 1]), double.Parse(points[i + 2]));
                newPath.Add(temporary);
            }

            return newPath;
        }
コード例 #18
0
ファイル: FileSystemArchive.cs プロジェクト: bspell1/SkyFloe
 /// <summary>
 /// Initializes a new archive instance
 /// </summary>
 /// <param name="path">
 /// The path to the archive subdirectory
 /// </param>
 public FileSystemArchive(IO.Path path)
 {
     this.Path = path;
      var restoreIndexPath = new IO.Path(
     Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
     "SkyFloe",
     "FileStore",
     this.Name,
     "restore.db"
      );
      IO.FileSystem.CreateDirectory(restoreIndexPath.Parent);
      this.restoreIndex = (IO.FileSystem.GetMetadata(restoreIndexPath).Exists) ?
     Sqlite.RestoreIndex.Open(restoreIndexPath) :
     Sqlite.RestoreIndex.Create(restoreIndexPath, new Restore.Header());
 }
コード例 #19
0
        public static Path LoadPath(string filePath)
        {
            var path = new Path();
            using (var reader = new StreamReader(filePath))
            {
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    Point3D point = Point3D.Parse(line);
                    path.AddPoint(point);
                }
            }

            return path;
        }
コード例 #20
0
ファイル: LongPathCommon.cs プロジェクト: DotNetIO/DotNetIO
        internal static bool Exists(Path path, out bool isDirectory)
        {
            string normalizedPath;
            if (TryNormalizeLongPath(path.FullPath, out normalizedPath))
            {
                FileAttributes attributes;
                var errorCode = TryGetFileAttributes(normalizedPath, out attributes);
                if (errorCode == 0)
                {
                    isDirectory = LongPathDirectory.IsDirectory(attributes);
                    return true;
                }
            }

            isDirectory = false;
            return false;
        }
コード例 #21
0
ファイル: MouvmlWriter.cs プロジェクト: Araxor/mouvtor
        public void AddPath(Path path)
        {
            var PathElement = new XElement("path", new XAttribute("timestamp", path.Timestamp));

            foreach (var step in path)
            {
                PathElement.Add(new XElement(
                    "point",
                    new XAttribute("x", step.NormalizedPosition.X),
                    new XAttribute("y", step.NormalizedPosition.Y),
                    new XAttribute("z", step.NormalizedPosition.Z),
                    new XAttribute("timestamp", step.Timestamp)
                ));
            }

            RootElement.Add(PathElement);
        }
コード例 #22
0
ファイル: PathStorage.cs プロジェクト: rsmont/OOP
 public static Path LoadPath(string filePath)
 {
     Path tempPath = new Path();
     Point3d point = new Point3d();
     using (var reader = new StreamReader(filePath))
     {
         int i = 0;
         for (string line; (line = reader.ReadLine()) != null; i++)
         {
             string[] points = line.Split(',');
             point.PointX = double.Parse(points[0]);
             point.PointY = double.Parse(points[1]);
             point.PointZ = double.Parse(points[2]);
             tempPath.Add(point);
         }
     }
     return tempPath;
 }
コード例 #23
0
ファイル: FileSystemModel.cs プロジェクト: GibSral/fitsharp
        public string GetPageContent(Path thePath)
        {
            try {
                using (var file = new FileStream(thePath.ToString(), FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) {
                    using (var reader = new StreamReader(file, encoding)) {
                        return reader.ReadToEnd();
                    }
                }
            }
            catch (FileNotFoundException) {
                // File does not exist, return null
            }
            catch (DirectoryNotFoundException) {
                // File's parent directory does not exist, return null
            }

            return null;
        }
コード例 #24
0
        // reads path from file
        // file format is:
        // at first line - N, the number of points into the path
        // at each consecutive N lines - point coordinates X, Y, Z, separated by spaces
        public static Path Read(string filename)
        {
            Path result = new Path();
            using (StreamReader sr = new StreamReader(filename)) // if something goes wrong, a standard exception procedure will take place
            {
                int cnt = int.Parse(sr.ReadLine()); // reads number of points of the path
                for (int i = 0; i < cnt; i++)
                {
                    string[] coords = sr.ReadLine().Split(' '); // reads each point (X,Y,Z, separated by spaces)
                    int x = int.Parse(coords[0]);
                    int y = int.Parse(coords[1]);
                    int z = int.Parse(coords[2]);
                    result.Add(x, y, z); // and loads it into the path
                }
            }

            return result; // finally returns the path
        }
コード例 #25
0
        public static void SaveToFile(Path path)
        {
            // First assign writer and file to save in
            // True so we can append many paths
            StreamWriter writer = new StreamWriter("../../SavedPaths.txt", true);

            using (writer)
            {
                // Define variable length outside the loop so there's no need to be calculated at every iteration
                int length = path.Paths.Count;

                for (int i = 0; i < length; i++)
                {
                    // Our path has a List of elements of Point3D
                    // WriteLine works because of overriding ToString
                    writer.WriteLine(path.Paths[i]);
                }

                // To separate different paths
                writer.WriteLine("*");

            }
        }
コード例 #26
0
        // static methods to save and load paths from a text file
        public static List<Path> LoadPaths(string pathFile)
        {
            var result = new List<Path>();

            try
            {
                using (StreamReader sr = new StreamReader(@"..\..\Paths\" + pathFile + ".txt"))
                {
                    string line = sr.ReadLine();
                    while (line != null)
                    {
                        Path thisPath = new Path(line);
                        result.Add(thisPath);
                        line = sr.ReadLine();
                    }
                }
            }
            catch(FileNotFoundException)
            {
                Console.Write("The path \"{0}\" cannot be found.", pathFile);
                return null;
            }
            return result;
        }
コード例 #27
0
        private void FillTreeView(string sourceDir, string[] svgFiles, TreeViewItem treeItem)
        {
            if (svgFiles != null && svgFiles.Length != 0)
            {
                for (int i = 0; i < svgFiles.Length; i++)
                {
                    string svgFile = svgFiles[i];

                    TextBlock itemText = new TextBlock();
                    itemText.Text   = string.Format("({0:D3}) - {1}", i, IoPath.GetFileName(svgFile));
                    itemText.Margin = new Thickness(3, 0, 0, 0);

                    BulletDecorator fileItem = new BulletDecorator();
                    if (_fileThumbnail != null)
                    {
                        Image image = new Image();
                        image.Source = _fileThumbnail;
                        image.Height = 16;
                        image.Width  = 16;

                        fileItem.Bullet = image;
                    }
                    else
                    {
                        Ellipse bullet = new Ellipse();
                        bullet.Height          = 16;
                        bullet.Width           = 16;
                        bullet.Fill            = Brushes.Goldenrod;
                        bullet.Stroke          = Brushes.DarkGray;
                        bullet.StrokeThickness = 1;

                        fileItem.Bullet = bullet;
                    }
                    fileItem.Margin = new Thickness(0, 0, 10, 0);
                    fileItem.Child  = itemText;

                    TreeViewItem item = new TreeViewItem();
                    item.Tag        = svgFile;
                    item.Header     = fileItem;
                    item.Margin     = new Thickness(0);
                    item.Padding    = new Thickness(2);
                    item.FontSize   = 12;
                    item.FontWeight = FontWeights.Normal;

                    treeItem.Items.Add(item);
                }
            }

            if (string.IsNullOrWhiteSpace(sourceDir) || !Directory.Exists(sourceDir))
            {
                return;
            }

            if (_optionSettings.RecursiveSearch == false)
            {
                return;
            }

            string[] directories = Directory.GetDirectories(sourceDir);
            if (directories != null && directories.Length != 0)
            {
                for (int i = 0; i < directories.Length; i++)
                {
                    string directory = directories[i];
                    svgFiles = Directory.GetFiles(directory, SvgFilePattern, SearchOption.TopDirectoryOnly);
                    {
                        DirectoryInfo directoryInfo = new DirectoryInfo(directory);

                        TextBlock headerText = new TextBlock();
                        headerText.Text   = directoryInfo.Name;
                        headerText.Margin = new Thickness(3, 0, 0, 0);

                        BulletDecorator decorator = new BulletDecorator();
                        if (_folderClose != null)
                        {
                            Image image = new Image();
                            image.Source = _folderClose;

                            decorator.Bullet = image;
                        }
                        else
                        {
                            Ellipse bullet = new Ellipse();
                            bullet.Height          = 16;
                            bullet.Width           = 16;
                            bullet.Fill            = Brushes.Goldenrod;
                            bullet.Stroke          = Brushes.DarkGray;
                            bullet.StrokeThickness = 1;

                            decorator.Bullet = bullet;
                        }
                        decorator.Margin = new Thickness(0, 0, 10, 0);
                        decorator.Child  = headerText;

                        TreeViewItem categoryItem = new TreeViewItem();
                        categoryItem.Tag        = string.Empty;
                        categoryItem.Header     = decorator;
                        categoryItem.Margin     = new Thickness(0);
                        categoryItem.Padding    = new Thickness(3);
                        categoryItem.FontSize   = 14;
                        categoryItem.FontWeight = FontWeights.Bold;

                        treeItem.Items.Add(categoryItem);

                        FillTreeView(directory, svgFiles, categoryItem);

                        if (!categoryItem.HasItems)
                        {
                            treeItem.Items.Remove(categoryItem);
                        }
                    }
                }
            }
        }
コード例 #28
0
ファイル: MainWindow.xaml.cs プロジェクト: nemesv/ASTRA.EMSG
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string userDirectory = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);

                string packageResourceName      = "ASTRA.EMSG.Mobile.Installer.InstallerPackage.Application.pkg";
                string packageName              = "Application.pkg";
                string applicationDirectoryName = "EMSG.Mobile";
                string applicationName          = "ASTRA.EMSG.Mobile.exe";

                string installDirectory = System.IO.Path.Combine(userDirectory, applicationDirectoryName);
                if (!Directory.Exists(installDirectory))
                {
                    Directory.CreateDirectory(installDirectory);
                }

                string packageFilePath = Path.Combine(installDirectory, packageName);

                string applicationPath = Path.Combine(installDirectory, applicationName);

                using (Stream resourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(packageResourceName))
                {
                    using (var fw = new FileStream(packageFilePath, FileMode.Create))
                    {
                        byte[] bytes = ReadAllByte(resourceStream);
                        fw.Write(bytes, 0, bytes.Length);
                    }
                }

                var packaging = new Packaging.Packaging();

                var worker = new BackgroundWorker();
                worker.DoWork +=
                    (s, a) =>
                {
                    Dispatcher.Invoke(new Action(() =>
                    {
                        InstallStep.Visibility  = Visibility.Collapsed;
                        ProgressStep.Visibility = Visibility.Visible;
                    }));
                    ReturnResult returnResult = packaging.UncompressFile(installDirectory, packageFilePath, true);
                    if (returnResult.Success)
                    {
                        CreateIcon("EMSG Mobile", applicationPath);
                        SetLanguageInConfig(applicationPath);
                    }
                };
                worker.RunWorkerCompleted += (s, a) =>
                {
                    Dispatcher.Invoke(new Action(() =>
                    {
                        ProgressStep.Visibility =
                            Visibility.Collapsed;
                        SuccessStep.Visibility =
                            Visibility.Visible;
                    }));
                };
                worker.RunWorkerAsync();
            }
            catch (Exception ex)
            {
                using (var file = File.CreateText("errorlog.txt"))
                {
                    file.WriteLine(string.Format("{0} - {1}", DateTime.Now, ex));
                }
            }
        }
コード例 #29
0
 new = ExceptionsViewModel(new TransactionContextCreator(Path.Combine(ApplicationData.Current.LocalFolder.Path, @"server.sqlite")).Create, ExceptionsSettings.Default);
コード例 #30
0
ファイル: ResumeForm.cs プロジェクト: gitter-badger/ORTS-MG
        private static void DeleteSavePoint(SavePoint savePoint)
        {
            if (null != savePoint)
            {
                if (!Directory.Exists(UserSettings.DeletedSaveFolder))
                {
                    Directory.CreateDirectory(UserSettings.DeletedSaveFolder);
                }

                foreach (string fileName in Directory.EnumerateFiles(Path.GetDirectoryName(savePoint.File), savePoint.Name + ".*"))
                {
                    try
                    {
                        File.Move(fileName, Path.Combine(UserSettings.DeletedSaveFolder, Path.GetFileName(fileName)));
                    }
                    catch (Exception ex) when(ex is IOException || ex is FileNotFoundException || ex is UnauthorizedAccessException)
                    {
                    }
                }
            }
        }
コード例 #31
0
        private void ImportSkinPackButton_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog()
            {
                Filter = "MCPACK Files (*.mcpack)|*.mcpack|ZIP Files (*.zip)|*.zip"
            };

            if (dialog.ShowDialog().Value)
            {
                try
                {
                    var file = ZipFile.OpenRead(dialog.FileName);
                    if (file.Entries.ToList().Exists(x => x.FullName == "skins.json"))
                    {
                        file.Dispose();
                        string InstallationPath     = Filepaths.GetInstallationsFolderPath(ConfigManager.CurrentProfile, ConfigManager.CurrentInstallation.DirectoryName);
                        string NewPackDirectoryName = Path.GetFileNameWithoutExtension(Path.GetRandomFileName());
                        string NewPackDirectory     = Path.Combine(Filepaths.GetSkinPacksFolderPath(InstallationPath, false), NewPackDirectoryName);

                        while (Directory.Exists(NewPackDirectory))
                        {
                            NewPackDirectoryName = Path.GetFileNameWithoutExtension(Path.GetRandomFileName());
                            NewPackDirectory     = Path.Combine(Filepaths.GetSkinPacksFolderPath(InstallationPath, false), NewPackDirectoryName);
                        }

                        ZipFile.ExtractToDirectory(dialog.FileName, NewPackDirectory);
                    }
                    else
                    {
                        file.Dispose();
                        ErrorScreenShow.errormsg("notaskinpack");
                    }
                }
                catch (Exception ex)
                {
                    ErrorScreenShow.exceptionmsg(ex);
                }
            }
            ReloadSkinPacks();
        }
コード例 #32
0
ファイル: Class1.cs プロジェクト: Xeltica/Groorine_1
 public async Task <IFile> GetFileAsync(string name) => await Task.Factory.StartNew(() => new File(P.Combine(Path, name)));
コード例 #33
0
        public FileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options)
        {
            if (path == null)
            {
                throw new ArgumentNullException(nameof(path), SR.ArgumentNull_Path);
            }
            if (path.Length == 0)
            {
                throw new ArgumentException(SR.Argument_EmptyPath, nameof(path));
            }

            // don't include inheritable in our bounds check for share
            FileShare tempshare = share & ~FileShare.Inheritable;
            string    badArg    = null;

            if (mode < FileMode.CreateNew || mode > FileMode.Append)
            {
                badArg = nameof(mode);
            }
            else if (access < FileAccess.Read || access > FileAccess.ReadWrite)
            {
                badArg = nameof(access);
            }
            else if (tempshare < FileShare.None || tempshare > (FileShare.ReadWrite | FileShare.Delete))
            {
                badArg = nameof(share);
            }

            if (badArg != null)
            {
                throw new ArgumentOutOfRangeException(badArg, SR.ArgumentOutOfRange_Enum);
            }

            // NOTE: any change to FileOptions enum needs to be matched here in the error validation
            if (options != FileOptions.None && (options & ~(FileOptions.WriteThrough | FileOptions.Asynchronous | FileOptions.RandomAccess | FileOptions.DeleteOnClose | FileOptions.SequentialScan | FileOptions.Encrypted | (FileOptions)0x20000000 /* NoBuffering */)) != 0)
            {
                throw new ArgumentOutOfRangeException(nameof(options), SR.ArgumentOutOfRange_Enum);
            }

            if (bufferSize <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedPosNum);
            }

            // Write access validation
            if ((access & FileAccess.Write) == 0)
            {
                if (mode == FileMode.Truncate || mode == FileMode.CreateNew || mode == FileMode.Create || mode == FileMode.Append)
                {
                    // No write access, mode and access disagree but flag access since mode comes first
                    throw new ArgumentException(SR.Format(SR.Argument_InvalidFileModeAndAccessCombo, mode, access), nameof(access));
                }
            }

            if ((access & FileAccess.Read) != 0 && mode == FileMode.Append)
            {
                throw new ArgumentException(SR.Argument_InvalidAppendMode, nameof(access));
            }

            string fullPath = Path.GetFullPath(path);

            _path         = fullPath;
            _access       = access;
            _bufferLength = bufferSize;

            if ((options & FileOptions.Asynchronous) != 0)
            {
                _useAsyncIO = true;
            }

            _fileHandle = OpenHandle(mode, share, options);

            try
            {
                Init(mode, share);
            }
            catch
            {
                // If anything goes wrong while setting up the stream, make sure we deterministically dispose
                // of the opened handle.
                _fileHandle.Dispose();
                _fileHandle = null;
                throw;
            }
        }
コード例 #34
0
        private void DoStartup()
        {
            string videoPathInSolution = Path.Combine(Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.Parent.FullName, "Video");

            Helper.CloneDirectory(videoPathInSolution, videoServerURL);
        }
コード例 #35
0
        public AnalysisView(
            string dbDir,
            Version version     = null,
            bool withContention = false,
            bool withRecursion  = false
            )
        {
            var paths = new List <string>();

            paths.Add(dbDir);
            while (!File.Exists(IOPath.Combine(paths[0], "__builtin__.idb")) &&
                   !File.Exists(IOPath.Combine(paths[0], "builtins.idb")))
            {
                var upOne = IOPath.GetDirectoryName(paths[0]);
                if (string.IsNullOrEmpty(upOne) || upOne == paths[0])
                {
                    break;
                }
                paths.Insert(0, upOne);
            }

            if (withRecursion)
            {
                paths.AddRange(Directory.EnumerateDirectories(dbDir, "*", SearchOption.AllDirectories));
            }

            if (version == null)
            {
                if (File.Exists(IOPath.Combine(paths[0], "builtins.idb")))
                {
                    version = new Version(3, 3);
                }
                else
                {
                    version = new Version(2, 7);
                }
            }

            _factory = InterpreterFactoryCreator.CreateAnalysisInterpreterFactory(
                version,
                dbDir,
                paths.ToArray()
                );
            Path         = dbDir;
            _interpreter = _factory.CreateInterpreter();
            _context     = _interpreter.CreateModuleContext();

            var modNames = _interpreter.GetModuleNames();
            IEnumerable <Tuple <string, string> > modItems;

            if (!withRecursion)
            {
                modItems = modNames
                           .Select(n => Tuple.Create(n, IOPath.Combine(dbDir, n + ".idb")))
                           .Where(t => File.Exists(t.Item2));
            }
            else
            {
                modItems = modNames
                           .Select(n => Tuple.Create(
                                       n,
                                       Directory.EnumerateFiles(dbDir, n + ".idb", SearchOption.AllDirectories).FirstOrDefault()
                                       ))
                           .Where(t => File.Exists(t.Item2));
            }

            var stopwatch = new Stopwatch();

            stopwatch.Start();
            if (withContention)
            {
                modItems = modItems
                           .AsParallel()
                           .WithExecutionMode(ParallelExecutionMode.ForceParallelism);
            }
            _modules = modItems
                       .Select(t => new ModuleView(_interpreter, _context, t.Item1, t.Item2))
                       .OrderBy(m => m.SortKey)
                       .ThenBy(m => m.Name)
                       .ToList <IAnalysisItemView>();
            stopwatch.Stop();

            _modules.Insert(0, new KnownTypesView(_interpreter, version));

            LoadMilliseconds    = stopwatch.ElapsedMilliseconds;
            TopLevelModuleCount = _modules.Count - 1;
        }
コード例 #36
0
        public override void SummariseResults(
            AnalysisSettings analysisSettings,
            FileSegment inputFileSegment,
            EventBase[] events,
            SummaryIndexBase[] indices,
            SpectralIndexBase[] spectralIndices,
            AnalysisResult2[] results)
        {
            // below is example of how to access values in ContentDescription config file.
            //sampleRate = analysisSettings.Configuration.GetIntOrNull(AnalysisKeys.ResampleRate) ?? sampleRate;
            var cdConfiguration     = (CdConfig)analysisSettings.Configuration;
            var ldSpectrogramConfig = cdConfiguration.LdSpectrogramConfig;

            //var cdConfigFile = analysisSettings.ConfigFile;
            //var configDirectory = cdConfigFile.DirectoryName ?? throw new ArgumentNullException(nameof(cdConfigFile), "Null value");
            var    sourceAudio      = inputFileSegment.Source;
            string basename         = Path.GetFileNameWithoutExtension(sourceAudio.Name);
            var    resultsDirectory = AnalysisCoordinator.GetNamedDirectory(analysisSettings.AnalysisOutputDirectory, this);

            // check for null values - this was recommended by ReSharper!
            if (inputFileSegment.TargetFileDuration == null || inputFileSegment.TargetFileSampleRate == null)
            {
                throw new NullReferenceException();
            }

            // output config data to disk so other analyzers can use the data,
            // Should contain data only - i.e. the configuration settings that generated these indices
            // this data can then be used by later analysis processes.
            var indexConfigData = new IndexGenerationData()
            {
                RecordingExtension            = inputFileSegment.Source.Extension,
                RecordingBasename             = basename,
                RecordingStartDate            = inputFileSegment.TargetFileStartDate,
                RecordingDuration             = inputFileSegment.TargetFileDuration.Value,
                SampleRateOriginal            = inputFileSegment.TargetFileSampleRate.Value,
                SampleRateResampled           = ContentSignatures.SampleRate,
                FrameLength                   = ContentSignatures.FrameSize,
                FrameStep                     = ContentSignatures.FrameSize,
                IndexCalculationDuration      = TimeSpan.FromSeconds(ContentSignatures.IndexCalculationDurationInSeconds),
                BgNoiseNeighbourhood          = TimeSpan.FromSeconds(5), // default value for content description
                AnalysisStartOffset           = inputFileSegment.SegmentStartOffset ?? TimeSpan.Zero,
                MaximumSegmentDuration        = analysisSettings.AnalysisMaxSegmentDuration,
                BackgroundFilterCoeff         = SpectrogramConstants.BACKGROUND_FILTER_COEFF,
                LongDurationSpectrogramConfig = ldSpectrogramConfig,
            };
            var icdPath = FilenameHelpers.AnalysisResultPath(
                resultsDirectory,
                basename,
                IndexGenerationData.FileNameFragment,
                "json");

            Json.Serialise(icdPath.ToFileInfo(), indexConfigData);

            // gather spectra to form spectrograms.  Assume same spectra in all analyzer results
            var dictionaryOfSpectra = spectralIndices.ToTwoDimensionalArray(SpectralIndexValuesForContentDescription.CachedSelectors, TwoDimensionalArray.Rotate90ClockWise);

            // Calculate the index distribution statistics and write to a json file. Also save as png image
            // The following method returns var indexDistributions =, but we have no use for them.
            IndexDistributions.WriteSpectralIndexDistributionStatistics(dictionaryOfSpectra, resultsDirectory, basename);

            // Draw ldfc spectrograms and return path to 2maps image.
            string ldfcSpectrogramPath =
                DrawSpectrogramsFromSpectralIndices(
                    ldSpectrogramConfig,
                    outputDirectory: resultsDirectory,
                    indexGenerationData: indexConfigData,
                    basename: basename,
                    indexSpectrograms: dictionaryOfSpectra);

            // Gather the content description results into an array of DescriptionResult and then convert to dictionary
            var allContentDescriptionResults = results.Select(x => (DescriptionResult)x.MiscellaneousResults[nameof(DescriptionResult)]);
            var contentDictionary            = DataProcessing.ConvertResultsToDictionaryOfArrays(allContentDescriptionResults.ToList());

            // Write the results to a csv file
            var filePath = Path.Combine(resultsDirectory.FullName, "AcousticSignatures.csv");

            // TODO: fix this so it writes header and a column of content description values.
            //Csv.WriteToCsv(new FileInfo(filePath), contentDictionary);
            FileTools.WriteDictionaryAsCsvFile(contentDictionary, filePath);

            // prepare graphical plots of the acoustic signatures.
            var contentPlots = GetPlots(contentDictionary);
            var images       = GraphsAndCharts.DrawPlotDistributions(contentPlots);
            var plotsImage   = ImageTools.CombineImagesVertically(images);

            plotsImage.Save(Path.Combine(resultsDirectory.FullName, "DistributionsOfContentScores.png"));

            // Attach content description plots to LDFC spectrogram and write to file
            var ldfcSpectrogram = Image.Load <Rgb24>(ldfcSpectrogramPath);
            var image           = ContentVisualization.DrawLdfcSpectrogramWithContentScoreTracks(ldfcSpectrogram, contentPlots);
            var path3           = Path.Combine(resultsDirectory.FullName, basename + ".ContentDescription.png");

            image.Save(path3);
        }
コード例 #37
0
 private void Nav_Up(object sender, RoutedEventArgs e)
 {
     Task.Run(() => LoadPath(Path.GetDirectoryName(CurrentPath)));
 }
コード例 #38
0
        private async Task Process(LayestaInfo level)
        {
PROCESS:
            try
            {
                var basefilename = setting.SaveAsGuid ? level.GUID : string.Format("[{0}] {1}", level.Charter, level.SongName);
                foreach (char c in Path.GetInvalidFileNameChars())
                {
                    basefilename = basefilename.Replace(c, '_');
                }

                var layestafile = Path.Combine(setting.SavePath, basefilename + ".layesta");

                if (!File.Exists(layestafile) || setting.AllowOverwrite)
                {
                    await MainWindow.API.DownloadChart(level.GUID, layestafile);
                }

                if (setting.SaveAsLap)
                {
                    string lappath = Path.Combine(setting.SavePath, basefilename);
                    if (Directory.Exists(lappath))
                    {
                        if (setting.AllowOverwrite)
                        {
                            Directory.Delete(lappath, true);
                        }
                        else
                        {
                            Current += 1;
                            return;
                        }
                    }
                    Directory.CreateDirectory(lappath);

                    bool ExtractResult = false;
                    await Task.Run(() => {
                        try
                        {
                            ZipFile.ExtractToDirectory(layestafile, lappath);
                            ExtractResult = true;
                        }
                        catch (InvalidDataException)
                        {
                            File.Delete(layestafile);
                        }
                        catch (Exception ex)
                        {
                            Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate { ErrorWindow.ShowException(ex, true); }));
                            Current += 1;
                        }
                    });

                    if (!ExtractResult)
                    {
                        goto PROCESS;
                    }

                    File.Delete(layestafile);
                    File.Delete(Path.Combine(lappath, "background_blur.png"));
                    File.Delete(Path.Combine(lappath, "info.bytes"));

                    var lap    = new LapFile();
                    var charts = new List <string>();
                    foreach (var file in Directory.GetFiles(lappath))
                    {
                        var filename = System.IO.Path.GetFileName(file);
                        if (lap.BGA0Path == null && filename.Equals("background_gray.jpg"))
                        {
                            lap.BGA0Path = file;
                        }
                        if (lap.BGA1Path == null && filename.Equals("background_linear.jpg"))
                        {
                            lap.BGA1Path = file;
                        }
                        if (Path.GetExtension(file).Equals(".txt"))
                        {
                            var    b64name        = filename.Replace("chart_", "").Replace(".txt", "");
                            string decode_b64name = Encoding.UTF8.GetString(Convert.FromBase64String(b64name)) + ".txt";
                            File.Move(file, Path.Combine(lappath, decode_b64name));
                            charts.Add(decode_b64name);
                        }
                    }

                    await Task.Run(() =>
                    {
                        var mp3file = Path.Combine(lappath, "music.mp3");
                        AudioConverter.MP3ToOGG(mp3file, Path.Combine(lappath, Path.Combine(lappath, "music.ogg")));
                        File.Delete(mp3file);
                    });


                    var basebgpath = Path.Combine(lappath, "background.jpg");
                    if (lap.BGA0Path == null)
                    {
                        lap.BGA0Path = basebgpath;
                    }
                    else if (lap.BGA1Path == null)
                    {
                        lap.BGA1Path = basebgpath;
                    }
                    else
                    {
                        lap.BGA2Path = basebgpath;
                    }

                    lap.Name          = level.SongName;
                    lap.Designer      = level.Charter;
                    lap.ProjectFolder = lappath;
                    lap.MusicPath     = Path.Combine(lappath, "music.ogg");
                    lap.ChartPath     = charts.First();

                    File.WriteAllText(Path.Combine(lappath, basefilename + ".lap"), lap.Serialization());

                    if (setting.SaveAsZip)
                    {
                        var zippath = Path.Combine(setting.SavePath, basefilename + ".zip");
                        if (File.Exists(zippath))
                        {
                            File.Delete(zippath);
                        }

                        ZipFile.CreateFromDirectory(lappath, Path.Combine(setting.SavePath, basefilename + ".zip"));
                        Directory.Delete(lappath, true);
                    }
                }
                Current += 1;
            }
            catch (LayestaWebAPINeedLoginException ex)
            {
                var mw = Owner as MainWindow;
                mw.TryLogin();

                goto PROCESS; //goto fuckyeah!!!!
            }
            catch (InvalidDataException ex)
            {
                Console.WriteLine(ex.Source);
                File.Delete(ex.Source);
                goto PROCESS;
            }
            catch (Exception ex)
            {
                Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate { ErrorWindow.ShowException(ex, true); }));
                Current += 1;
            }
            finally
            {
                Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate { Progress.Value = (double)(Current / Total * 100.0); }));
            }
        }
コード例 #39
0
        /// <summary>
        /// This converts the SVG resource specified by the Uri to <see cref="DrawingGroup"/>.
        /// </summary>
        /// <param name="svgSource">A <see cref="Uri"/> specifying the source of the SVG resource.</param>
        /// <returns>A <see cref="DrawingGroup"/> of the converted SVG resource.</returns>
        private DrawingGroup GetDrawing(Uri svgSource)
        {
            WpfDrawingSettings settings = new WpfDrawingSettings();

            settings.IncludeRuntime = false;
            settings.TextAsGeometry = true;
            settings.OptimizePath   = true;

            StreamResourceInfo svgStreamInfo = null;

            if (svgSource.ToString().IndexOf("siteoforigin", StringComparison.OrdinalIgnoreCase) >= 0)
            {
                svgStreamInfo = Application.GetRemoteStream(svgSource);
            }
            else
            {
                svgStreamInfo = Application.GetResourceStream(svgSource);
            }

            Stream svgStream = (svgStreamInfo != null) ? svgStreamInfo.Stream : null;

            if (svgStream != null)
            {
                string fileExt      = IoPath.GetExtension(svgSource.ToString());
                bool   isCompressed = !string.IsNullOrWhiteSpace(fileExt) && string.Equals(
                    fileExt, SvgConverter.CompressedSvgExt, StringComparison.OrdinalIgnoreCase);

                if (isCompressed)
                {
                    using (svgStream)
                    {
                        using (var zipStream = new GZipStream(svgStream, CompressionMode.Decompress))
                        {
                            using (FileSvgReader reader = new FileSvgReader(settings))
                            {
                                DrawingGroup drawGroup = reader.Read(zipStream);

                                if (drawGroup != null)
                                {
                                    return(drawGroup);
                                }
                            }
                        }
                    }
                }
                else
                {
                    using (svgStream)
                    {
                        using (FileSvgReader reader = new FileSvgReader(settings))
                        {
                            DrawingGroup drawGroup = reader.Read(svgStream);

                            if (drawGroup != null)
                            {
                                return(drawGroup);
                            }
                        }
                    }
                }
            }

            return(null);
        }
コード例 #40
0
        private void OnWindowClosing(object sender, CancelEventArgs e)
        {
            string backupFile = null;

            if (File.Exists(_testSettingsPath))
            {
                backupFile = IoPath.ChangeExtension(_testSettingsPath, SvgConverter.BackupExt);
                try
                {
                    if (File.Exists(backupFile))
                    {
                        File.Delete(backupFile);
                    }
                    File.Move(_testSettingsPath, backupFile);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString(), AppErrorTitle, MessageBoxButton.OK, MessageBoxImage.Error);

                    return;
                }
            }
            try
            {
                _optionSettings.Save(_testSettingsPath);
            }
            catch (Exception ex)
            {
                if (File.Exists(backupFile))
                {
                    File.Move(backupFile, _testSettingsPath);
                }

                MessageBox.Show(ex.ToString(), AppErrorTitle, MessageBoxButton.OK, MessageBoxImage.Error);
            }
            if (!string.IsNullOrWhiteSpace(backupFile) && File.Exists(backupFile))
            {
                File.Delete(backupFile);
            }

            try
            {
                if (_canDeleteXaml && !string.IsNullOrWhiteSpace(_xamlFilePath) && File.Exists(_xamlFilePath))
                {
                    File.Delete(_xamlFilePath);
                }
                if (!string.IsNullOrWhiteSpace(_drawingDir) && Directory.Exists(_drawingDir))
                {
                    string[] imageFiles = Directory.GetFiles(_drawingDir, "*.png");
                    if (imageFiles != null && imageFiles.Length != 0)
                    {
                        foreach (var imageFile in imageFiles)
                        {
                            File.Delete(imageFile);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Trace.TraceError(ex.ToString());
            }

            if (_debugPage != null)
            {
                _debugPage.Shutdown();
            }
        }
コード例 #41
0
ファイル: AssimpProvider.cs プロジェクト: Bananaman043/cbre
        protected override DataStructures.Models.Model LoadFromFile(IFile file)
        {
            if (importer == null)
            {
                importer = new AssimpContext();
                //importer.SetConfig(new NormalSmoothingAngleConfig(66.0f));
            }

            DataStructures.Models.Model model = new DataStructures.Models.Model();
            DataStructures.Models.Bone  bone  = new DataStructures.Models.Bone(0, -1, null, "rootBone", CoordinateF.Zero, CoordinateF.Zero, CoordinateF.One, CoordinateF.One);
            model.Bones.Add(bone);

            Scene scene = importer.ImportFile(file.FullPathName);

            DataStructures.Models.Texture tex = null;

            if (scene.MaterialCount > 0)
            {
                //TODO: handle several textures
                for (int i = 0; i < scene.MaterialCount; i++)
                {
                    if (string.IsNullOrEmpty(scene.Materials[i].TextureDiffuse.FilePath))
                    {
                        continue;
                    }
                    string path = Path.Combine(Path.GetDirectoryName(file.FullPathName), scene.Materials[i].TextureDiffuse.FilePath);
                    if (!File.Exists(path))
                    {
                        path = scene.Materials[i].TextureDiffuse.FilePath;
                    }
                    if (File.Exists(path))
                    {
                        Bitmap bmp = new Bitmap(path);
                        tex = new DataStructures.Models.Texture
                        {
                            Name   = path,
                            Index  = 0,
                            Width  = bmp.Width,
                            Height = bmp.Height,
                            Flags  = 0,
                            Image  = bmp
                        };
                    }
                    break;
                }
            }

            if (tex == null)
            {
                Bitmap bmp = new Bitmap(64, 64);
                for (int i = 0; i < 64; i++)
                {
                    for (int j = 0; j < 64; j++)
                    {
                        bmp.SetPixel(i, j, Color.DarkGray);
                    }
                }
                tex = new DataStructures.Models.Texture
                {
                    Name   = "blank",
                    Index  = 0,
                    Width  = 64,
                    Height = 64,
                    Flags  = 0,
                    Image  = bmp
                };
            }

            model.Textures.Add(tex);

            AddNode(scene, scene.RootNode, model, tex, Matrix4x4.Identity);

            return(model);
        }
コード例 #42
0
ファイル: TemporaryDirectory.cs プロジェクト: jnm2/corefx
    private static DirectoryInfo CreateTemporaryDirectoryInfo()
    {
        string path = IOPath.Combine(TestInfo.CurrentDirectory, IOPath.GetRandomFileName());

        return(Directory.CreateDirectory(path));
    }
コード例 #43
0
ファイル: Class1.cs プロジェクト: Xeltica/Groorine_1
 public async Task <IFolder> GetFolderAsync(string name) => await Task.Factory.StartNew(() => new Folder(P.Combine(Path, name)));
コード例 #44
0
        protected override void ProcessRecord()
        {
            var isLiteral = LiteralPath != null && LiteralPath.Length > 0;

            foreach (var path in ResolvePaths(isLiteral ? LiteralPath : Path, isLiteral))
            {
                IgnoreRules.Clear();
                // If the current path is a file, handle it in a special way.
                if (!path.Attributes.HasFlag(FileAttributes.Directory))
                {
                    // skip out early if the file is an ignore file and those aren't included.
                    if (path.Name == IgnoreFileName && !IncludeIgnoreFiles)
                    {
                        continue;
                    }
                    AddIgnorePatterns(((FileInfo)path).DirectoryName.Replace('\\', '/'));
                    ProcessFileSystemItem(path);

                    // then, skip ahead to write out any directories for this item, and continue.
                    goto WriteDirectories;
                }

                // otherwise, clean up for the next run
                Queue.Clear();
                IgnoreRulePerDirectoryCounts.Clear();
                DirectoryHasValidChildren.Clear();

                // add the next item and begin.
                Queue.AddFirst((DirectoryInfo)path);

                uint currentDepth    = 0;
                var  ignoreRuleCount = AddIgnorePatterns(Regex.Escape(Queue.First.Value.FullName.Replace('\\', '/')));;
                while (Queue.Count > 0)
                {
                    var nextNode = Queue.First;
                    var top      = nextNode.Value;

                    if (IgnoreRulePerDirectoryCounts.ContainsKey(top.FullName))
                    {
                        // If this is the second time we've seen this node, remove the rules
                        // for this directory from the list. Then, remove this directory from
                        // the map (we won't see it again, so save some memory).
                        ignoreRuleCount = IgnoreRulePerDirectoryCounts[top.FullName];
                        for (; ignoreRuleCount > 0; ignoreRuleCount -= 1)
                        {
                            IgnoreRules.RemoveFirst();
                        }
                        IgnoreRulePerDirectoryCounts.Remove(top.FullName);
                        Queue.RemoveFirst();
                        currentDepth -= 1;

                        if (DirectoryHasValidChildren.ContainsKey(top.FullName))
                        {
                            // If directories are being output, push them onto a stack.
                            // Directories are re-encountered in reverse order, so they
                            // need to be re-reversed before being output.
                            OutputDirectories.Push(top);
                            DirectoryHasValidChildren[top.Parent.FullName] = true;
                            DirectoryHasValidChildren.Remove(top.FullName);
                        }
                        continue;
                    }

                    currentDepth += 1;

                    // First, look for the ignore file if there is one.
                    if (!string.IsNullOrEmpty(IgnoreFileName))
                    {
                        var ignoreFile = new FileInfo(IOPath.Combine(top.FullName, IgnoreFileName));
                        if (ignoreFile.Exists && !ignoreFile.Attributes.HasFlag(FileAttributes.Directory))
                        {
                            var basePath = Regex.Escape(top.FullName.Replace('\\', '/'));
                            using (var reader = new StreamReader(ignoreFile.OpenRead()))
                                // Process each line of the file as a new rule.
                                for (var line = reader.ReadLine(); null != line; line = reader.ReadLine())
                                {
                                    ignoreRuleCount += AddPatternRule(basePath, line);
                                }
                        }
                    }

                    // For each directory in our stack from where we are now up to the root of the search,
                    // we keep track of how many rules were added in that directory. The next time this
                    // directory is at the front of the queue, all its children will have been processed,
                    // so we can remove the rules associated with this directory.
                    IgnoreRulePerDirectoryCounts[top.FullName] = ignoreRuleCount;
                    ignoreRuleCount = 0;

                    // Then, for each file or directory...
                    var skipRemainingFiles = false;
                    using (var entries = top.EnumerateFileSystemInfos().GetEnumerator())
                        while (entries.MoveNext())
                        {
                            skipRemainingFiles = ProcessFileSystemItem(entries.Current, currentDepth, nextNode, skipRemainingFiles);
                        }
                }

WriteDirectories:
                // If there are directories to output, output them in the right order.
                while (OutputDirectories.Count > 0)
                {
                    WriteObject(OutputDirectories.Pop());
                }
            }
        }
コード例 #45
0
ファイル: ResumeForm.cs プロジェクト: gitter-badger/ORTS-MG
        /// <summary>
        /// Saves may come from other, foreign installations (i.e. not this PC).
        /// They can be replayed or resumed on this PC but they will contain activity / path / consist filenames
        /// and these may be inappropriate for this PC, typically having a different path.
        /// This method tries to use the paths in the SavePoint if they exist on the current PC.
        /// If not, it prompts the user to locate a matching file from those on the current PC.
        ///
        /// The save file is then modified to contain filename(s) from the current PC instead.
        /// </summary>
        private bool Found(SavePoint save)
        {
            if (SelectedAction == MainForm.UserAction.SinglePlayerTimetableGame)
            {
                return(true); // no additional actions required for timetable resume
            }
            else
            {
                string[] savedArgs = Array.Empty <string>();
                try
                {
                    using (BinaryReader inf = new BinaryReader(new FileStream(save.File, FileMode.Open, FileAccess.Read)))
                    {
                        string version      = inf.ReadString();
                        string routeName    = inf.ReadString();
                        string pathName     = inf.ReadString();
                        int    gameTime     = inf.ReadInt32();
                        long   realTime     = inf.ReadInt64();
                        float  currentTileX = inf.ReadSingle();
                        float  currentTileZ = inf.ReadSingle();
                        float  initialTileX = inf.ReadSingle();
                        float  initialTileZ = inf.ReadSingle();
                        int    tempInt      = inf.ReadInt32();
                        savedArgs = new string[tempInt];
                        for (int i = 0; i < savedArgs.Length; i++)
                        {
                            savedArgs[i] = inf.ReadString();
                        }

                        // Re-locate files if saved on another PC
                        bool rewriteNeeded = false;
                        // savedArgs[0] contains Activity or Path filepath
                        string filePath = savedArgs[0];
                        if (!File.Exists(filePath))
                        {
                            // Show the dialog and get result.
                            openFileDialog1.InitialDirectory = FolderStructure.Current.Folder;
                            openFileDialog1.FileName         = Path.GetFileName(filePath);
                            openFileDialog1.Title            = catalog.GetString($"Find location for file {filePath}");
                            if (openFileDialog1.ShowDialog() != DialogResult.OK)
                            {
                                return(false);
                            }
                            rewriteNeeded = true;
                            savedArgs[0]  = openFileDialog1.FileName;
                        }
                        if (savedArgs.Length > 1)  // Explore, not Activity
                        {
                            // savedArgs[1] contains Consist filepath
                            filePath = savedArgs[1];
                            if (!File.Exists(filePath))
                            {
                                // Show the dialog and get result.
                                openFileDialog1.InitialDirectory = FolderStructure.Current.Folder;
                                openFileDialog1.FileName         = Path.GetFileName(filePath);
                                openFileDialog1.Title            = catalog.GetString($"Find location for file {filePath}");
                                if (openFileDialog1.ShowDialog() != DialogResult.OK)
                                {
                                    return(false);
                                }
                                rewriteNeeded = true;
                                savedArgs[1]  = openFileDialog1.FileName;
                            }
                        }
                        if (rewriteNeeded)
                        {
                            using (BinaryWriter outf = new BinaryWriter(new FileStream(save.File + ".tmp", FileMode.Create, FileAccess.Write)))
                            {
                                // copy the start of the file
                                outf.Write(version);
                                outf.Write(routeName);
                                outf.Write(pathName);
                                outf.Write(gameTime);
                                outf.Write(realTime);
                                outf.Write(currentTileX);
                                outf.Write(currentTileZ);
                                outf.Write(initialTileX);
                                outf.Write(initialTileZ);
                                outf.Write(savedArgs.Length);
                                // copy the pars which may have changed
                                for (int i = 0; i < savedArgs.Length; i++)
                                {
                                    outf.Write(savedArgs[i]);
                                }
                                // copy the rest of the file
                                while (inf.BaseStream.Position < inf.BaseStream.Length)
                                {
                                    outf.Write(inf.ReadByte());
                                }
                            }
                            inf.Close();
                            File.Replace(save.File + ".tmp", save.File, null);
                        }
                        else
                        {
                            inf.Close();
                        }
                    }
                }
                catch (Exception ex) when(ex is IOException || ex is FileNotFoundException)
                {
                    MessageBox.Show(catalog.GetString($"Could not change file location from {save.File} to {savedArgs.FirstOrDefault()}."));
                }
            }
            return(true);
        }
コード例 #46
0
        private void Apply_Click(object sender, RoutedEventArgs e)
        {
            var main = ((MainViewModel)DataContext).Main;

            if (main.FileNameChange && !(main.FileNameSuratNumber || main.FileNameSuratName))
            {
                MessageBox.Show("إذا أردت تغيير إسم الملف، فعليك إختيار رقم السورة أو اسمها أو كليهما.", "تنبيه", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            if (main.TitleChange && !(main.TitleSuratNumber || main.TitleSuratName))
            {
                MessageBox.Show("إذا أردت تغيير ال عنوان، فعليك إختيار رقم السورة أو اسمها أو كليهما.", "تنبيه", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            uint year = 0;

            if (main.YearChange)
            {
                try
                {
                    year = uint.Parse(main.Year);
                }
                catch (Exception exception)
                {
                    MessageBox.Show("السنة التي ادخلتها غير صحيحة.", "تنبيه", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }
            }

            foreach (var file in main.Files)
            {
                var resultString = Regex.Match(main.RecorgnizeByFileName ? file.Name : file.File.Tag.Title, @"\d+").Value;
                if (resultString.Length > 0)
                {
                    var index = int.Parse(resultString);

                    if (main.TitleChange)
                    {
                        file.File.Tag.Title = "";
                        if (main.TitleSuratNumber)
                        {
                            file.File.Tag.Title = index.ToString("000");
                        }
                        if (main.TitleSuratNumber && main.TitleSuratName)
                        {
                            file.File.Tag.Title += " - ";
                        }
                        if (main.TitleSuratName)
                        {
                            file.File.Tag.Title += main.TitleStyle.Values[index - 1];
                        }
                    }

                    if (main.ArtistChange)
                    {
                        file.File.Tag.AlbumArtists = new [] { main.Artist };
                    }

                    if (main.AlbumChange)
                    {
                        file.File.Tag.Album = main.Album;
                    }

                    if (main.YearChange)
                    {
                        file.File.Tag.Year = year;
                    }

                    file.File.Save();

                    if (main.FileNameChange)
                    {
                        var fileName = "";
                        if (main.TitleSuratNumber)
                        {
                            fileName = index.ToString("000");
                        }
                        if (main.TitleSuratNumber && main.TitleSuratName)
                        {
                            fileName += " - ";
                        }
                        if (main.TitleSuratName)
                        {
                            fileName += main.TitleStyle.Values[index - 1];
                        }
                        fileName = Path.Combine(main.Path, $"{fileName}.mp3");

                        System.IO.File.Move(file.File.Name, fileName);
                        //file = new MP3File(fileName);
                    }
                }
            }

            MessageBox.Show("تمت المهمة بنجاح..", "تنبيه", MessageBoxButton.OK, MessageBoxImage.Information);
        }
コード例 #47
0
ファイル: ResumeForm.cs プロジェクト: gitter-badger/ORTS-MG
 private async void ButtonUndelete_Click(object sender, EventArgs e)
 {
     if (Directory.Exists(UserSettings.DeletedSaveFolder))
     {
         foreach (string filePath in Directory.EnumerateFiles(UserSettings.DeletedSaveFolder))
         {
             try
             {
                 File.Move(filePath, Path.Combine(UserSettings.UserDataFolder, Path.GetFileName(filePath)));
             }
             catch (Exception ex) when(ex is IOException || ex is FileNotFoundException || ex is UnauthorizedAccessException)
             {
             }
         }
         Directory.Delete(UserSettings.DeletedSaveFolder);
     }
     await LoadSavePointsAsync().ConfigureAwait(true);
 }
コード例 #48
0
 public TempDirectory()
 {
     Path = IOPath.Combine(IOPath.GetTempPath(), IOPath.GetRandomFileName());
     Directory.CreateDirectory(Path);
 }
コード例 #49
0
        // Try to guess suitable variables for build files, references and resources
        void GuessVariables()
        {
            ICollection <string> vars = TryGetVariables(false);

            if (vars == null)
            {
                return;
            }

            string files_var = GetActiveVar(comboFilesVar);
            string res_var   = GetActiveVar(comboResourcesVar);
            string ref_var   = GetActiveVar(comboPackageRefVar);

            string prefix;

            foreach (string var in vars)
            {
                if (ref_var.Length > 0 && res_var.Length > 0 && files_var.Length > 0)
                {
                    break;
                }

                if (files_var.Length == 0 && CheckSourceCode(data.Makefile.GetListVariable(var)))
                {
                    files_var = var;
                    SetFilesVariable(files_var);
                    continue;
                }

                if (res_var.Length == 0 && CheckRes(data.Makefile.GetListVariable(var), out prefix))
                {
                    res_var = var;
                    SetResourcesVariable(res_var, prefix);
                    continue;
                }

                // We only try to find one variable for references
                if (ref_var.Length == 0 && CheckRefs(data.Makefile.GetListVariable(var), out prefix))
                {
                    ref_var = var;
                    SetReferencesVariable(ref_var, prefix);
                    continue;
                }
            }

            // Try to guess using some common variable names
            if (files_var.Length == 0)
            {
                string [] files_var_names = { "FILES" };

                foreach (string var in files_var_names)
                {
                    if (data.Makefile.GetListVariable(var) != null)
                    {
                        SetFilesVariable(var);
                        break;
                    }
                }
            }

            //as these vars would've been already selected if a valid prefix was there
            if (res_var.Length == 0)
            {
                string [] res_var_names = { "RESOURCES", "RES" };

                foreach (string var in res_var_names)
                {
                    if (data.Makefile.GetListVariable(var) != null)
                    {
                        SetResourcesVariable(var, GuessResPrefix(data.Makefile.GetListVariable(var)));
                        break;
                    }
                }
            }

            if (ref_var.Length == 0)
            {
                string [] ref_var_names = { "REFERENCES", "REFS" };

                foreach (string var in ref_var_names)
                {
                    if (data.Makefile.GetListVariable(var) != null)
                    {
                        SetReferencesVariable(var, GuessRefPrefix(data.Makefile.GetListVariable(var)));
                        break;
                    }
                }
            }

            // Try to find configure.(in|ac) string
            string path = FindConfigureScript(SPath.GetDirectoryName(data.AbsoluteMakefileName));

            if (path != null)
            {
                fileEntryConfigureInPath.Path = fileEntryConfigureInPath.DefaultPath = SPath.GetDirectoryName(path);
                cbAutotoolsProject.Active     = true;
                HandleCbAutotoolsProjectClicked(cbAutotoolsProject);
            }
        }
コード例 #50
0
 public static void SavePaths(Path points, string filePath)
 {
     File.WriteAllText(filePath, points.ToString());
 }
コード例 #51
0
        public MainWindow()
        {
            string[] args = Environment.GetCommandLineArgs();
            if (args.Length < 2)
            {
                string           message   = "You must provide a valid PRG Maker project file to continue.";
                string           caption   = "RPG Maker Plugin Help Viewer";
                MessageBoxButton msgButton = MessageBoxButton.OKCancel;
                MessageBoxImage  msgImage  = MessageBoxImage.Exclamation;

                MessageBoxResult result = MessageBox.Show(message, caption, msgButton, msgImage);
                switch (result)
                {
                case MessageBoxResult.OK:
                    OpenFileDialog openFileDialog = new OpenFileDialog();
                    openFileDialog.Filter           = "RPG Maker Projects (*.rpgproject)|*.rpgproject";
                    openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                    if (openFileDialog.ShowDialog() == true)
                    {
                        ProjectFile = openFileDialog.FileName;
                    }
                    else
                    {
                        App.Current.Shutdown();
                    }
                    break;

                case MessageBoxResult.Cancel:
                    App.Current.Shutdown();
                    break;
                }
            }
            else if (args.Length > 2)
            {
                for (var i = 1; i < args.Length; i++)
                {
                    if (i > 1)
                    {
                        ProjectFile += " ";
                    }
                    ProjectFile += args[i];
                }
            }
            else
            {
                ProjectFile = args[1];
            }
            PluginsPath      = Path.GetDirectoryName(ProjectFile) + @"\js\plugins";
            PluginConfigFile = Path.GetDirectoryName(ProjectFile) + @"\js\plugins.js";

            InitializeComponent();
            BoldEnabled        = (bool)tbBold.IsChecked;
            ProjectIcon.Source = MySystemIcons.ToImageSource(MySystemIcons.FolderFilesIcon);
            RefreshIcon.Source = MySystemIcons.ToImageSource(MySystemIcons.RefreshIcon);

            if (HelpTextBlock != null)
            {
                HelpTextBlockActive = true;
            }
            int[]    intFontSizes = { 8, 9, 10, 11, 12, 14, 16, 18, 20, 22, 24, 26, 28, 36, 48, 72 };
            string[] strFontSizes = intFontSizes.Select(x => x.ToString()).ToArray();
            cmbFontSize.ItemsSource = strFontSizes;
            Get_Plugins();
        }
コード例 #52
0
ファイル: FileDump.cs プロジェクト: CurtHagenlocher/OrcSharp
 public bool accept(Path p)
 {
     String name = p.getName();
     return !name.startsWith("_") && !name.startsWith(".") && !name.endsWith(
         AcidUtils.DELTA_SIDE_FILE_SUFFIX);
 }
コード例 #53
0
ファイル: Program.cs プロジェクト: vuhoangminh/smartd
        ////////////////////////////////////////////////

        static Path MakeRandomPolygon(Random r,  int maxWidth, int maxHeight, int edgeCount, Int64 scale = 1)
        {
            Path result = new Path(edgeCount);
            for (int i = 0; i < edgeCount; i++)
            {
                result.Add(new IntPoint(r.Next(maxWidth)*scale, r.Next(maxHeight)*scale));
            }
            return result;
        }
コード例 #54
0
 bool IsDll(string file)
 {
     return(SPath.GetExtension(file).ToUpper() == ".DLL");
 }
コード例 #55
0
        internal static async Task Start()
        {
            if (KestrelWebHost != null)
            {
                return;
            }

            ASF.ArchiLogger.LogGenericInfo(Strings.IPCStarting);

            // The order of dependency injection matters, pay attention to it
#if NETFRAMEWORK
            WebHostBuilder builder = new();
#else
            HostBuilder builder = new();
#endif

            string customDirectory  = Path.Combine(Directory.GetCurrentDirectory(), SharedInfo.WebsiteDirectory);
            string websiteDirectory = Directory.Exists(customDirectory) ? customDirectory : Path.Combine(AppContext.BaseDirectory, SharedInfo.WebsiteDirectory);

            // Set default content root
            builder.UseContentRoot(SharedInfo.HomeDirectory);

            // Firstly initialize settings that user is free to override
            builder.ConfigureLogging(
                logging => {
                logging.ClearProviders();
                logging.SetMinimumLevel(Debugging.IsUserDebugging ? LogLevel.Trace : LogLevel.Warning);
            }
                );

            // Check if custom config is available
            string absoluteConfigDirectory = Path.Combine(Directory.GetCurrentDirectory(), SharedInfo.ConfigDirectory);
            string customConfigPath        = Path.Combine(absoluteConfigDirectory, SharedInfo.IPCConfigFile);

            bool customConfigExists = File.Exists(customConfigPath);

            if (customConfigExists)
            {
                if (Debugging.IsDebugConfigured)
                {
                    try {
                        string json = await Compatibility.File.ReadAllTextAsync(customConfigPath).ConfigureAwait(false);

                        if (!string.IsNullOrEmpty(json))
                        {
                            JObject jObject = JObject.Parse(json);

                            ASF.ArchiLogger.LogGenericDebug(SharedInfo.IPCConfigFile + ": " + jObject.ToString(Formatting.Indented));
                        }
                    } catch (Exception e) {
                        ASF.ArchiLogger.LogGenericException(e);
                    }
                }

                // Use custom config for logging configuration
                builder.ConfigureLogging((hostingContext, logging) => logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging")));
            }

            // Enable NLog integration for logging
            builder.UseNLog();

            builder.ConfigureWebHostDefaults(
                webBuilder => {
                // Set default web root
                webBuilder.UseWebRoot(websiteDirectory);

                // Now conditionally initialize settings that are not possible to override
                if (customConfigExists)
                {
                    // Set up custom config to be used
                    webBuilder.UseConfiguration(new ConfigurationBuilder().SetBasePath(absoluteConfigDirectory).AddJsonFile(SharedInfo.IPCConfigFile, false, Program.ConfigWatch).Build());

                    // Use custom config for Kestrel configuration
                    webBuilder.UseKestrel((builderContext, options) => options.Configure(builderContext.Configuration.GetSection("Kestrel")));
                }
                else
                {
                    // Use ASF defaults for Kestrel
                    webBuilder.UseKestrel(options => options.ListenLocalhost(1242));
                }

                // Specify Startup class for IPC
                webBuilder.UseStartup <Startup>();
            }
                );

            // Init history logger for /Api/Log usage
            Logging.InitHistoryLogger();

            // Start the server
#if NETFRAMEWORK
            IWebHost?kestrelWebHost = null;
#else
            IHost?kestrelWebHost = null;
#endif

            try {
                kestrelWebHost = builder.Build();
                await kestrelWebHost.StartAsync().ConfigureAwait(false);
            } catch (Exception e) {
                ASF.ArchiLogger.LogGenericException(e);
                kestrelWebHost?.Dispose();

                return;
            }

            KestrelWebHost = kestrelWebHost;
            ASF.ArchiLogger.LogGenericInfo(Strings.IPCReady);
        }
コード例 #56
0
        private async Task LoadFile(string fileName)
        {
            string fileExt = IoPath.GetExtension(fileName);

            if (string.IsNullOrWhiteSpace(fileExt))
            {
                return;
            }

            bool generateXaml = _optionSettings.ShowOutputFile;

            if (string.Equals(fileExt, SvgConverter.SvgExt, StringComparison.OrdinalIgnoreCase) ||
                string.Equals(fileExt, SvgConverter.CompressedSvgExt, StringComparison.OrdinalIgnoreCase))
            {
                _svgFilePath = fileName;

                if (_svgPage != null && _optionSettings.ShowInputFile)
                {
                    _svgPage.LoadDocument(fileName);
                }

                if (_drawingPage == null)
                {
                    return;
                }
                _drawingPage.SaveXaml = generateXaml;

                try
                {
                    if (await _drawingPage.LoadDocumentAsync(fileName))
                    {
                        this.Title = AppTitle + " - " + IoPath.GetFileName(fileName);

                        if (_xamlPage != null && !string.IsNullOrWhiteSpace(_drawingDir))
                        {
                            string xamlFilePath = IoPath.Combine(_drawingDir,
                                                                 IoPath.GetFileNameWithoutExtension(fileName) + SvgConverter.XamlExt);

                            _xamlFilePath  = xamlFilePath;
                            _canDeleteXaml = true;

                            if (File.Exists(xamlFilePath) && _optionSettings.ShowOutputFile)
                            {
                                _xamlPage.LoadDocument(xamlFilePath);
                            }
                        }

                        _fileWatcher.Path = IoPath.GetDirectoryName(fileName);
                        // Only watch current file
                        _fileWatcher.Filter = IoPath.GetFileName(fileName);
                        // Begin watching.
                        _fileWatcher.EnableRaisingEvents = true;
                    }
                }
                catch
                {
                    // Try loading the XAML, if generated but the rendering failed...
                    if (_xamlPage != null && !string.IsNullOrWhiteSpace(_drawingDir))
                    {
                        string xamlFilePath = IoPath.Combine(_drawingDir,
                                                             IoPath.GetFileNameWithoutExtension(fileName) + SvgConverter.XamlExt);

                        _xamlFilePath  = xamlFilePath;
                        _canDeleteXaml = true;

                        if (File.Exists(xamlFilePath) && _optionSettings.ShowOutputFile)
                        {
                            _xamlPage.LoadDocument(xamlFilePath);
                        }
                    }
                    throw;
                }
            }
        }
コード例 #57
0
        private void StartBatchButtonButton_Click(object sender, RoutedEventArgs e)
        {
            bool isDup = false;

            //check input from users;
            if (ActionListBox.Items.Count == 0)
            {
                System.Windows.Forms.MessageBox.Show("Add Method Before Batching!", "Erro Detected in Input", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error);
            }
            else if (FileTab.Items.Count == 0 && FolderTab.Items.Count == 0)
            {
                System.Windows.Forms.MessageBox.Show("Choose File Or Folder Before Batching!", "Erro Detected in Input", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error);
            }
            else
            {
                ObservableCollection <File>   FileList   = new ObservableCollection <File>();
                ObservableCollection <Folder> FolderList = new ObservableCollection <Folder>();
                //file process
                foreach (File file in FileTab.Items)
                {
                    string result = file.Filename;

                    foreach (StringAction action in ActionListBox.Items)
                    {
                        result = action.Processor.Invoke(result);
                    }

                    var path = Path.GetDirectoryName(file.Path);
                    try
                    {
                        var tempfile = new FileInfo(file.Path);
                        tempfile.MoveTo(path + "\\" + result);
                        file.Newfilename = result;
                    }
                    catch (Exception k)
                    {
                        isDup            = true;
                        file.Newfilename = result;
                        file.Erro        = "Duplicate";
                        FileList.Add(file);
                    }
                }
                //folder process
                int count = 0;
                foreach (Folder folder in FolderTab.Items)
                {
                    string result = folder.Foldername;

                    foreach (StringAction action in ActionListBox.Items)
                    {
                        result = action.Processor.Invoke(result);
                    }
                    string newfolderpath  = Path.GetDirectoryName(folder.Path) + "\\" + result;
                    string tempFolderName = "\\Temp";
                    string tempFolderPath = Path.GetDirectoryName(folder.Path) + tempFolderName;
                    CopyAll(folder.Path, tempFolderPath, true);

                    if (folder.Path.Equals(newfolderpath) == false)
                    {
                        RemoveDirectory(folder.Path);
                        Directory.Delete(folder.Path);
                        try
                        {
                            Directory.Move(tempFolderPath, newfolderpath);
                            folder.Newfolder = result;
                            folder.Erro      = "OK";
                        }
                        catch (Exception exception) //exception when folder name is duplicate
                        {
                            string duplicatestore = Path.GetDirectoryName(folder.Path) + "\\Store" + $"{++count}";
                            CopyAll(tempFolderPath, duplicatestore, true);
                            RemoveDirectory(tempFolderPath);
                            Directory.Delete(tempFolderPath);
                            isDup            = true;
                            folder.Newfolder = result;
                            folder.Erro      = "Duplicate Foldername";
                            FolderList.Add(folder);
                        }
                    }
                    else
                    {
                        RemoveDirectory(tempFolderPath);
                        Directory.Delete(tempFolderPath);
                    }
                }

                if (isDup == true)
                {
                    var dupscreen = new DuplicateProcess(FileList, FolderList);
                    dupscreen.ShowDialog();
                }
                var screen = new preview(FileTab.Items, FolderTab.Items);
                screen.ShowDialog();
                FolderTab.Items.Refresh();
                FileTab.Items.Refresh();
            }
        }
コード例 #58
0
ファイル: Class1.cs プロジェクト: Xeltica/Groorine_1
 public File(string path)
 {
     Name = P.GetFileName(path);
     Path = path;
 }
コード例 #59
0
        private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
        {
            var canvas = control1.Template.LoadContent() as Canvas;

            File.WriteAllText(Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "temp"), XamlWriter.Save(canvas));
        }
コード例 #60
0
 public string GetPackageDirectory(string packageId, SemanticVersion version)
 {
     return(IOPath.Combine(_path.FullName, packageId));
 }