private async void CreateFolder(string folderName) { if (string.IsNullOrWhiteSpace(folderName)) { MessageBox.Show("Invalid folder name"); return; } List <char> invalidChars = Path.GetInvalidFileNameChars().ToList(); invalidChars.AddRange(Path.GetInvalidPathChars().ToList()); foreach (char c in invalidChars) { if (folderName.Contains(c)) { MessageBox.Show(string.Format("value '{0}' is invalid for name", c)); return; } } CreatingFolderTextBlock.Visibility = Visibility.Visible; try { await Utils.FTPMakeFolderAsync(string.Format("{0}{1}", FTPPath, folderName), Credential); } catch (Exception ex) { MessageBox.Show(ex.ToString()); return; } FTPReturnFolderName = folderName; FTPReturnPath = string.Format("{0}{1}/", FTPPath, folderName); DialogResult = true; Close(); }
public static string SanitizeFilename(this string filename) { var sanitizedFilename = filename; var illegalChars = Path.GetInvalidFileNameChars().Select(c => c.ToString()); illegalChars.ForEach(c => sanitizedFilename = sanitizedFilename.Replace(c, "")); return(sanitizedFilename); }
public static void SaveImage(this IEnumerable <IPath> shapes, params string[] path) { IPath shape = new ComplexPolygon(shapes.ToArray()); shape = shape.Translate(shape.Bounds.Location * -1) // touch top left .Translate(new Vector2(10)); // move in from top left var sb = new StringBuilder(); IEnumerable <ISimplePath> converted = shape.Flatten(); converted.Aggregate(sb, (s, p) => { ReadOnlySpan <PointF> points = p.Points.Span; for (int i = 0; i < points.Length; i++) { PointF point = points[i]; sb.Append(point.X); sb.Append('x'); sb.Append(point.Y); sb.Append(' '); } s.Append('\n'); return(s); }); string str = sb.ToString(); shape = new ComplexPolygon(converted.Select(x => new Polygon(new LinearLineSegment(x.Points.ToArray()))).ToArray()); path = path.Select(p => IOPath.GetInvalidFileNameChars().Aggregate(p, (x, c) => x.Replace($"{c}", "-"))).ToArray(); string fullPath = IOPath.GetFullPath(IOPath.Combine("Output", IOPath.Combine(path))); // pad even amount around shape int width = (int)(shape.Bounds.Left + shape.Bounds.Right); int height = (int)(shape.Bounds.Top + shape.Bounds.Bottom); if (width < 1) { width = 1; } if (height < 1) { height = 1; } using var img = new Image <Rgba32>(width, height); img.Mutate(x => x.Fill(Color.DarkBlue)); img.Mutate(x => x.Fill(Color.HotPink, shape)); // img.Draw(Color.LawnGreen, 1, shape); // Ensure directory exists Directory.CreateDirectory(IOPath.GetDirectoryName(fullPath)); using FileStream fs = File.Create(fullPath); img.SaveAsPng(fs); }
public IFolder CreateSubfolder(string name) { var invalidChar = SysPath.GetInvalidFileNameChars().FirstOrDefault(ch => name.Contains(ch)); if (invalidChar != char.MinValue) { throw new ArgumentException("Name contains invalid character:" + invalidChar, nameof(name)); } return(new Folder(BaseStorageItem.CreateSubdirectory(name))); }
//获取有效文件名 public static string GetValidFileName(string input, string re = ".") { string title = input; foreach (char invalidChar in Path.GetInvalidFileNameChars()) { title = title.Replace(invalidChar.ToString(), re); } return(title); }
private string FixFileName(string pFileName) { var invalidChars = Path.GetInvalidFileNameChars(); if (pFileName.IndexOfAny(invalidChars) >= 0) { pFileName = invalidChars.Aggregate(pFileName, (current, invalidChar) => current.Replace(invalidChar, Convert.ToChar("_"))); } return(pFileName); }
/// <summary> /// Renames the current folder. This method also specifies what to do if an existing /// item in the current item's location has the same name. /// </summary> /// <param name="desiredName">The desired, new name of the current folder.</param> /// <param name="option"> /// The <see cref="Enum"/> value that determines how responds if the <see cref="desiredName"/> is the /// same as the name of an existing item in the current folder's location. /// Default value is "<see cref="NameCollisionOption.FailIfExists"/>". /// </param> public override void Rename(string desiredName, NameCollisionOption option = NameCollisionOption.FailIfExists) { var invalidChar = SysPath.GetInvalidFileNameChars().FirstOrDefault(ch => desiredName.Contains(ch)); if (invalidChar != char.MinValue) { throw new ArgumentException("Name contains invalid character:" + invalidChar, nameof(desiredName)); } Move(Parent, desiredName, option); }
private static string MakeValidFilename(string name) { if (Utils.IsNotBlank(name)) { foreach (char c in Path.GetInvalidFileNameChars()) { name = name.Replace(c.ToString(), "_"); } } return(name.Trim()); }
/// <summary> /// Determines whether <paramref name="name"/> is a valid name for a file. /// </summary> /// <param name="name">Filename to check.</param> /// <returns> /// <b>true</b> if <paramref name="name"/> is a valid file name; otherwise, <b>false</b>. /// </returns> public static bool IsValidFileName(string name) { Logger.Instance.Debug(""); Logger.Instance.Debug(" Assembly: iTin.Core.IO, Namespace: iTin.Core.IO, Class: File"); Logger.Instance.Debug(" Determines whether specified filename is a valid name for a file"); Logger.Instance.Debug($" > Signature: ({typeof(bool)}) IsValidFileName({typeof(string)})"); Logger.Instance.Debug($" > name: {name}"); bool result = NativePath.GetInvalidFileNameChars().All(c => !name.Contains(c.ToString(CultureInfo.InvariantCulture))); Logger.Instance.Debug($" > Output: {result}"); return(result); }
private bool IsProjectNameValidish(string path) { if (string.IsNullOrWhiteSpace(path)) { return(false); } var invalidChars = IOPath.GetInvalidFileNameChars(); if (path.Any(c => { return(invalidChars.Contains(c)); })) { return(false); } return(true); }
private static string MakeValidPath(string path) { if (Utils.IsNotBlank(path)) { path = FilenameUtils.separatorsToSystem(path); string prefix = FilenameUtils.getPrefix(path); if (!path.EndsWith(Path.DirectorySeparatorChar.ToString())) { path = path + Path.DirectorySeparatorChar; } path = FilenameUtils.getPath(path); StringBuilder sb = new StringBuilder(); if (Utils.IsNotBlank(prefix)) { sb.Append(prefix); } path = FilenameUtils.separatorsToSystem(path); string[] parts = path.Split(Path.DirectorySeparatorChar); foreach (string part in parts) { string cleanpart = part.Trim(); char[] invalidChars = Path.GetInvalidFileNameChars(); if (StringUtils.containsAny(cleanpart, invalidChars)) { foreach (char c in invalidChars) { cleanpart = cleanpart.Replace(c.ToString(), URIEncoder.encode(c.ToString())); } } sb.Append(cleanpart); if (!parts[parts.Length - 1].Equals(part)) { sb.Append(Path.DirectorySeparatorChar); } } return(sb.ToString()); } return(path); }
private void create_Click(object sender, RoutedEventArgs e) { bool cancel = false; string richTextBox1Text = new TextRange(richTextBox1.Document.ContentStart, richTextBox1.Document.ContentEnd).Text; if (textBox1.Text == "" || textBox1.Text.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0) { MessageBox.Show("You must type a valid file name!"); cancel = true; } if (richTextBox1Text == "") { MessageBox.Show("You must have some content in your config!"); cancel = true; } if (cancel == false) { if (isEditing == false) { addConfigContents = new TextRange(richTextBox1.Document.ContentStart, richTextBox1.Document.ContentEnd).Text; addConfigName = this.textBox1.Text; string file = Environment.CurrentDirectory + "\\Config\\" + addConfigName + ".ini"; string directory = Environment.CurrentDirectory + "\\Config"; DirectoryInfo di = Directory.CreateDirectory(directory); File.Create(file).Close(); File.WriteAllText(file, addConfigContents); this.DialogResult = true; } else { addConfigContents = new TextRange(richTextBox1.Document.ContentStart, richTextBox1.Document.ContentEnd).Text; addConfigName = this.textBox1.Text; String fileNew = Environment.CurrentDirectory + "\\Config\\" + addConfigName + ".ini"; if (addConfigName != originalName) { String fileOld = Environment.CurrentDirectory + "\\Config\\" + originalName + ".ini"; File.Move(fileOld, fileNew); } File.WriteAllText(fileNew, addConfigContents); this.DialogResult = true; } } }
public static void RenderText(Font font, string text, int width, int height) { string path = IOPath.GetInvalidFileNameChars().Aggregate(text, (x, c) => x.Replace($"{c}", "-")); string fullPath = IOPath.GetFullPath(IOPath.Combine("Output", IOPath.Combine(path))); using var img = new Image <Rgba32>(width, height); img.Mutate(x => x.Fill(Color.White)); IPathCollection shapes = TextBuilder.GenerateGlyphs(text, new TextOptions(font) { Origin = new Vector2(50f, 4f) }); img.Mutate(x => x.Fill(Color.Black, shapes)); Directory.CreateDirectory(IOPath.GetDirectoryName(fullPath)); using FileStream fs = File.Create(fullPath + ".png"); img.SaveAsPng(fs); }
private void btnSave_Click(object sender, MyClasses.MetaViewWrappers.MVControlEventArgs e) { try { string profileName = edtSaveAs.Text; char[] invalidChars = IOPath.GetInvalidFileNameChars(); foreach (char invalid in invalidChars) { if (profileName.Contains(invalid.ToString())) { string err = "The profile name can't contain any of the following characters:"; foreach (char invalid2 in invalidChars) { err += " " + invalid2; } Util.Error(err); return; } } SaveTabsXml(mSpellTabs, profileName, false); } catch (Exception ex) { Util.HandleException(ex); } }
public static bool IsFileNameValid(string input) { return(!Path.GetInvalidFileNameChars().Any(input.Contains)); }
private static string CreatePath(params string[] path) { path = path.Select(p => IOPath.GetInvalidFileNameChars().Aggregate(p, (x, c) => x.Replace($"{c}", "-"))).ToArray(); return(IOPath.GetFullPath(IOPath.Combine("Output", IOPath.Combine(path)))); }
private async void DownloadAudio(int position, string path) { if (position < 0 || position > queue.Count || queue[position].State != DownloadState.None) { return; } System.Console.WriteLine("&Downloading audio of: " + queue[position].Name); queue[position].State = DownloadState.Initialization; UpdateList(position); while (downloadCount >= maxDownload) { await Task.Delay(1000); } downloadCount++; currentStrike++; CreateNotification(queue[position].Name); try { YoutubeClient client = new YoutubeClient(); Video video = await client.GetVideoAsync(queue[position].YoutubeID); MediaStreamInfoSet mediaStreamInfo = await client.GetVideoMediaStreamInfosAsync(queue[position].YoutubeID); MediaStreamInfo streamInfo; if (mediaStreamInfo.Audio.Count > 0) { streamInfo = mediaStreamInfo.Audio.Where(x => x.Container == Container.Mp4).OrderBy(s => s.Bitrate).Last(); } else if (mediaStreamInfo.Muxed.Count > 0) { streamInfo = mediaStreamInfo.Muxed.Where(x => x.Container == Container.Mp4).OrderBy(x => x.Resolution).Last(); } else { queue[position].State = DownloadState.Error; downloadCount--; if (queue.Count != 0) { DownloadAudio(queue.FindIndex(x => x.State == DownloadState.None), path); } Playlist.instance?.Activity.RunOnUiThread(() => { Playlist.instance.CheckForSync(); }); return; } queue[position].State = DownloadState.Downloading; UpdateList(position); string title = video.Title; foreach (char c in Path.GetInvalidFileNameChars()) //Make the title a valid filename (remove /, \, : etc). { title = title.Replace(c, ' '); } string fileExtension = "m4a"; //audio only extension containing aac (audio codex of the mp4) string outpath = path; if (queue[position].PlaylistName != null) { outpath = Path.Combine(path, queue[position].PlaylistName); Directory.CreateDirectory(outpath); } string filePath = Path.Combine(outpath, title + "." + fileExtension); if (File.Exists(filePath)) { int i = 1; string defaultPath = filePath; do { filePath = Path.Combine(outpath, title + " (" + i + ")." + fileExtension); i++; }while (File.Exists(filePath)); } MediaStream input = await client.GetMediaStreamAsync(streamInfo); queue[position].Path = filePath; files.Add(filePath); FileStream output = File.Create(filePath); byte[] buffer = new byte[4096]; int byteReaded = 0; while (byteReaded < input.Length) { int read = await input.ReadAsync(buffer, 0, 4096); await output.WriteAsync(buffer, 0, read); byteReaded += read; UpdateProgressBar(position, byteReaded / input.Length); } output.Dispose(); queue[position].State = DownloadState.MetaData; UpdateList(position); if (queue.Count == 1) { SetNotificationProgress(100, true); } SetMetaData(position, video.Title, video.Author, video.Thumbnails); files.Remove(filePath); downloadCount--; if (queue.Count != 0) { DownloadAudio(queue.FindIndex(x => x.State == DownloadState.None), path); } Playlist.instance?.Activity.RunOnUiThread(() => { Playlist.instance.CheckForSync(); }); } catch (System.Net.Http.HttpRequestException) { MainActivity.instance.Timout(); Cancel(); } catch (DirectoryNotFoundException) { Handler handler = new Handler(Looper.MainLooper); handler.Post(() => { Toast.MakeText(Application.Context, Resource.String.download_path_error, ToastLength.Long).Show(); }); Cancel(); } catch { MainActivity.instance.UnknowError(ErrorCode.DL1); Cancel(); } }
private static string MakeValidFileName(string name) { string invalidChars = System.Text.RegularExpressions.Regex.Escape(new string(Path.GetInvalidFileNameChars())); string invalidRegStr = string.Format(@"([{0}]*\.+$)|([{0}]+)", invalidChars); return(System.Text.RegularExpressions.Regex.Replace(name, invalidRegStr, "")); }
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); })); } }
public static string FilterForFilename(this string text) => string.Join(string.Empty, text.Where(c => !Path.GetInvalidFileNameChars().Contains(c)));
private void buttonCreateShortcut_Click(object sender, RoutedEventArgs e) { #region Verify if (string.IsNullOrEmpty(textBoxShortcutName.Text)) { textBoxShortcutName.Focus(); // TODO: [NOTIFICATION] 파일 이름을 입력하세요. // 텍스트 박스 붉은 빛으로 깜빡이기 return; } char[] invalidFileNameChars = Path.GetInvalidFileNameChars(); int invalidCharIndex = textBoxShortcutName.Text.IndexOfAny(invalidFileNameChars); if (invalidCharIndex != -1) { int lastInvalidCharIndex = textBoxShortcutName.Text.LastIndexOfAny(invalidFileNameChars); textBoxShortcutName.Focus(); textBoxShortcutName.Select(invalidCharIndex, Math.Max(lastInvalidCharIndex - invalidCharIndex, 1)); // TODO: [NOTIFICATION] 파일 이름에 이상한 문자가 있습니다. 파일 이름에 다음의 문자들은 사용할 수 없습니다. invalidFileNameChars // 텍스트 박스 붉은 빛으로 깜빡이기 return; } #endregion try { string directory = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); string filename = textBoxShortcutName.Text; string description = "Execute Bibimbaaaaaab with custom arguments."; string arguments = textBoxCommandLine.Text; #region Create Shortcut if (directory.IndexOfAny(Path.GetInvalidPathChars()) != -1) { throw new ArgumentException("directory"); } if (filename.IndexOfAny(Path.GetInvalidFileNameChars()) != -1) { throw new ArgumentException("filename"); } WshShell shell = new WshShell(); string shortcutPath = Path.ChangeExtension(Path.Combine(directory, filename), "lnk"); IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(shortcutPath); shortcut.TargetPath = System.Reflection.Assembly.GetEntryAssembly().CodeBase; shortcut.WorkingDirectory = Path.GetDirectoryName(shortcut.TargetPath); shortcut.Arguments = arguments; shortcut.Description = description; shortcut.Save(); #endregion } catch (Exception ex) { // TODO: [NOTIFICATION] 바로가기를 만드는 중 문제가 발생하였습니다. throw ex; } // TODO: [NOTIFICATION] 성공하였습니다. // 버튼 주위에 툴팁 보여주기 textBoxShortcutName.Text = string.Empty; }
public void TestGetInvalidFileNameChars() => Assert.IsTrue(Pri.LongPath.Path.GetInvalidFileNameChars().SequenceEqual(Path.GetInvalidFileNameChars()));