System.IO.Path.GetInvalidFileNameChars()

Here are the examples of the csharp api System.IO.Path.GetInvalidFileNameChars() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

513 Examples 7

19 View Source File : FilenameProvider.cs
License : MIT License
Project Creator : 0xd4d

static string ReplaceInvalidFilenameChars(string candidate) {
			var invalidChars = Path.GetInvalidFileNameChars();
			if (candidate.IndexOfAny(invalidChars) < 0)
				return candidate;
			var sb = new System.Text.StringBuilder();
			foreach (var c in candidate) {
				if (Array.IndexOf(invalidChars, c) >= 0)
					sb.Append('-');
				else
					sb.Append(c);
			}
			return sb.ToString();
		}

19 View Source File : dlgAddVM.cs
License : MIT License
Project Creator : 86Box

private void btnAdd_Click(object sender, EventArgs e)
        {
            if (main.VMCheckIfExists(txtName.Text))
            {
                MessageBox.Show("A virtual machine with this name already exists. Please pick a different name.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (txtName.Text.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0)
            {
                MessageBox.Show("There are invalid characters in the name you specified. You can't use the following characters: \\ / : * ? \" < > |", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (existingVM && string.IsNullOrWhiteSpace(txtImportPath.Text))
            {
                MessageBox.Show("If you wish to import VM files, you must specify a path.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (existingVM)
            {
                main.VMImport(txtName.Text, txtDescription.Text, txtImportPath.Text, cbxOpenCFG.Checked, cbxStartVM.Checked);
            }
            else
            {
                main.VMAdd(txtName.Text, txtDescription.Text, cbxOpenCFG.Checked, cbxStartVM.Checked);
            }
            Close();
        }

19 View Source File : dlgAddVM.cs
License : MIT License
Project Creator : 86Box

private void txtName_TextChanged(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtName.Text))
            {
                btnAdd.Enabled = false;
                tipTxtName.Active = false;
            }
            else
            {
                if (txtName.Text.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0)
                {
                    btnAdd.Enabled = false;
                    lblPath1.Text = "Invalid path";
                    tipTxtName.Active = true;
                    tipTxtName.Show("You cannot use the following characters in the name: \\ / : * ? \" < > |", txtName, 20000);
                }
                else
                {
                    btnAdd.Enabled = true;
                    lblPath1.Text = main.cfgpath + txtName.Text;
                    tipLblPath1.SetToolTip(lblPath1, main.cfgpath + txtName.Text);
                }
            }
        }

19 View Source File : dlgCloneVM.cs
License : MIT License
Project Creator : 86Box

private void txtName_TextChanged(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtName.Text))
            {
                btnClone.Enabled = false;
                tipTxtName.Active = false;
            }
            else
            {
                if (txtName.Text.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0)
                {
                    btnClone.Enabled = false;
                    lblPath1.Text = "Invalid path";
                    tipTxtName.Active = true;
                    tipTxtName.Show("You cannot use the following characters in the name: \\ / : * ? \" < > |", txtName, 20000);
                }
                else
                {
                    btnClone.Enabled = true;
                    lblPath1.Text = main.cfgpath + txtName.Text;
                    tipLblPath1.SetToolTip(lblPath1, main.cfgpath + txtName.Text);
                }
            }
        }

19 View Source File : dlgCloneVM.cs
License : MIT License
Project Creator : 86Box

private void btnClone_Click(object sender, EventArgs e)
        {
            if (main.VMCheckIfExists(txtName.Text))
            {
                MessageBox.Show("A virtual machine with this name already exists. Please pick a different name.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (txtName.Text.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0)
            {
                MessageBox.Show("There are invalid characters in the name you specified. You can't use the following characters: \\ / : * ? \" < > |", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            //Just import stuff from the existing VM
            main.VMImport(txtName.Text, txtDescription.Text, oldPath, cbxOpenCFG.Checked, cbxStartVM.Checked);
            Close();
        }

19 View Source File : dlgEditVM.cs
License : MIT License
Project Creator : 86Box

private void btnApply_Click(object sender, EventArgs e)
        {
            //Check if a VM with this name already exists
            if (!originalName.Equals(txtName.Text) && main.VMCheckIfExists(txtName.Text))
            {
                MessageBox.Show("A virtual machine with this name already exists. Please pick a different name.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else if (txtName.Text.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0)
            {
                MessageBox.Show("There are invalid characters in the name you specified. You can't use the following characters: \\ / : * ? \" < > |", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                main.VMEdit(txtName.Text, txtDesc.Text);
                Close();
            }
        }

19 View Source File : Repository.cs
License : Apache License 2.0
Project Creator : AantCoder

public static string NormalizeLogin(string login)
        {
            char[] invalidFileChars = Path.GetInvalidFileNameChars();
            foreach (var c in invalidFileChars) if (login.Contains(c)) login = login.Replace(c, '_');
            return login.ToLowerInvariant();
        }

19 View Source File : MiscUtils.cs
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas

public static string GetSafeFileName(string fileName)
        {
            if (fileName == null)
            {
                return null;
            }
            foreach (char c in System.IO.Path.GetInvalidFileNameChars())
            {
                fileName = fileName.Replace(c, '_');
            }
            return fileName;
        }

19 View Source File : FileUtils.cs
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas

public static bool IsValidFileName(string fileName)
        {
            return  !string.IsNullOrEmpty(fileName) && fileName.IndexOfAny(Path.GetInvalidFileNameChars()) < 0;
        }

19 View Source File : PublishArtifact.cs
License : MIT License
Project Creator : actions

public async Task RunAsync(
            RunnerActionPluginExecutionContext context,
            CancellationToken token)
        {
            string artifactName = context.GetInput(PublishArtifactInputNames.ArtifactName, required: false);  // Back compat since we rename input `artifactName` to `name`
            if (string.IsNullOrEmpty(artifactName))
            {
                artifactName = context.GetInput(PublishArtifactInputNames.Name, required: true);
            }

            string targetPath = context.GetInput(PublishArtifactInputNames.Path, required: true);
            string defaultWorkingDirectory = context.GetGitHubContext("workspace");

            targetPath = Path.IsPathFullyQualified(targetPath) ? targetPath : Path.GetFullPath(Path.Combine(defaultWorkingDirectory, targetPath));

            if (String.IsNullOrWhiteSpace(artifactName))
            {
                throw new ArgumentException($"Artifact name can not be empty string");
            }

            if (Path.GetInvalidFileNameChars().Any(x => artifactName.Contains(x)))
            {
                throw new ArgumentException($"Artifact name is not valid: {artifactName}. It cannot contain '\\', '/', \"', ':', '<', '>', '|', '*', and '?'");
            }

            // Build ID
            string buildIdStr = context.Variables.GetValueOrDefault(SdkConstants.Variables.Build.BuildId)?.Value ?? string.Empty;
            if (!int.TryParse(buildIdStr, out int buildId))
            {
                throw new ArgumentException($"Run Id is not an Int32: {buildIdStr}");
            }

            string fullPath = Path.GetFullPath(targetPath);
            bool isFile = File.Exists(fullPath);
            bool isDir = Directory.Exists(fullPath);
            if (!isFile && !isDir)
            {
                // if local path is neither file nor folder
                throw new FileNotFoundException($"Path does not exist {targetPath}");
            }

            // Container ID
            string containerIdStr = context.Variables.GetValueOrDefault(SdkConstants.Variables.Build.ContainerId)?.Value ?? string.Empty;
            if (!long.TryParse(containerIdStr, out long containerId))
            {
                throw new ArgumentException($"Container Id is not an Int64: {containerIdStr}");
            }

            context.Output($"Uploading artifact '{artifactName}' from '{fullPath}' for run #{buildId}");

            FileContainerServer fileContainerHelper = new FileContainerServer(context.VssConnection, projectId: Guid.Empty, containerId, artifactName);
            var propertiesDictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);

            long size = 0;

            try
            {
                size = await fileContainerHelper.CopyToContainerAsync(context, fullPath, token);

                propertiesDictionary.Add("artifactsize", size.ToString());

                context.Output($"Uploaded '{size}' bytes from '{fullPath}' to server");
            }
            // if any of the results were successful, make sure to attach them to the build
            finally
            {
                // Definition ID is a dummy value only used by HTTP client routing purposes
                int definitionId = 1;

                PipelinesServer pipelinesHelper = new PipelinesServer(context.VssConnection);

                var artifact = await pipelinesHelper.replacedociateActionsStorageArtifactAsync(
                    definitionId,
                    buildId,
                    containerId,
                    artifactName,
                    size,
                    token);

                context.Output($"replacedociated artifact {artifactName} ({artifact.ContainerId}) with run #{buildId}"); 
            }
        }

19 View Source File : IOUtil.cs
License : MIT License
Project Creator : actions

public static string ResolvePath(String rootPath, String relativePath)
        {
            ArgUtil.NotNullOrEmpty(rootPath, nameof(rootPath));
            ArgUtil.NotNullOrEmpty(relativePath, nameof(relativePath));

            if (!Path.IsPathRooted(rootPath))
            {
                throw new ArgumentException($"{rootPath} should be a rooted path.");
            }

            if (relativePath.IndexOfAny(Path.GetInvalidPathChars()) > -1)
            {
                throw new InvalidOperationException($"{relativePath} contains invalid path characters.");
            }
            else if (Path.GetFileName(relativePath).IndexOfAny(Path.GetInvalidFileNameChars()) > -1)
            {
                throw new InvalidOperationException($"{relativePath} contains invalid folder name characters.");
            }
            else if (Path.IsPathRooted(relativePath))
            {
                throw new InvalidOperationException($"{relativePath} can not be a rooted path.");
            }
            else
            {
                rootPath = rootPath.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
                relativePath = relativePath.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);

                // Root the path
                relativePath = String.Concat(rootPath, Path.AltDirectorySeparatorChar, relativePath);

                // Collapse ".." directories with their parent, and skip "." directories.
                String[] split = relativePath.Split(new[] { Path.AltDirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries);
                var segments = new Stack<String>(split.Length);
                Int32 skip = 0;
                for (Int32 i = split.Length - 1; i >= 0; i--)
                {
                    String segment = split[i];
                    if (String.Equals(segment, ".", StringComparison.Ordinal))
                    {
                        continue;
                    }
                    else if (String.Equals(segment, "..", StringComparison.Ordinal))
                    {
                        skip++;
                    }
                    else if (skip > 0)
                    {
                        skip--;
                    }
                    else
                    {
                        segments.Push(segment);
                    }
                }

                if (skip > 0)
                {
                    throw new InvalidOperationException($"The file path {relativePath} is invalid");
                }

#if OS_WINDOWS
                if (segments.Count > 1)
                {
                    return String.Join(Path.DirectorySeparatorChar, segments);
                }
                else
                {
                    return segments.Pop() + Path.DirectorySeparatorChar;
                }
#else
                return Path.DirectorySeparatorChar + String.Join(Path.DirectorySeparatorChar, segments);
#endif
            }
        }

19 View Source File : SettingsWindowViewModel.cs
License : MIT License
Project Creator : adlez27

private void LoadRecList(string path)
        {
            Settings temp = new Settings(true);
            temp.ReadUnicode = ReadUnicode;
            temp.SplitWhitespace = SplitWhitespace;

            bool validContent = true;
            try
            {
                temp.RecListFile = path;
            }
            catch (Exception e)
            {
                validContent = false;
            }

            string invalidChar = "";
            bool containsInvalidChar = false;

            if (validContent)
            {
                foreach (RecLisreplacedem item in temp.RecList)
                {
                    foreach (char c in Path.GetInvalidFileNameChars())
                    {
                        if (item.Text.Contains(c))
                        {
                            validContent = false;
                            containsInvalidChar = true;
                            invalidChar += c;
                            break;
                        }
                    }
                }
            }

            if (validContent)
            {
                ReclistContentValid = "";
                validDict["RecListFile"] = true;
                RecListFile = path;
                newRecList = true;
                recList = temp.RecList;
            }
            else
            {
                if (containsInvalidChar)
                    ReclistContentValid = $"Reclist contains invalid character: {invalidChar}";
                else
                    ReclistContentValid = "Could not load reclist.";
                validDict["RecListFile"] = false;
            }
            this.RaisePropertyChanged("Valid");

        }

19 View Source File : EntityGridController.cs
License : MIT License
Project Creator : Adoxio

[HttpPost]
		[JsonHandlerError]
		[AjaxValidateAntiForgeryToken]
		public ActionResult DownloadAsExcel(string viewName, IEnumerable<LayoutColumn> columns, string base64SecureConfiguration, string sortExpression, string search, string filter,
			string metaFilter, int page = 1, int pageSize = DefaultPageSize, int timezoneOffset = 0)
		{
			var viewConfiguration = ConvertSecureStringToViewConfiguration(base64SecureConfiguration);

			if (viewConfiguration == null)
			{
				return new HttpStatusCodeResult(HttpStatusCode.Forbidden, ResourceManager.GetString("Invalid_Request"));
			}

			var dataAdapterDependencies = new PortalConfigurationDataAdapterDependencies(requestContext: Request.RequestContext, portalName: viewConfiguration.PortalName);

			// override the page parameters
			page = 1;
			pageSize = new SettingDataAdapter(dataAdapterDependencies, HttpContext.GetWebsite())
				.GetIntegerValue("Grid/Download/MaximumResults")
				.GetValueOrDefault(Fetch.MaximumPageSize);
			viewConfiguration.PageSize = pageSize;
			
			var json = GetData(viewConfiguration, sortExpression, search, filter, metaFilter, page, pageSize, true, false, null, null, null, null, true) as JsonResult;

			if (json == null)
			{
				return new HttpStatusCodeResult(HttpStatusCode.NoContent);
			}

			if (json.Data is EnreplacedyPermissionResult)
			{
				return json;
			}

			var data = json.Data as PaginatedGridData;

			if (data == null)
			{
				return new HttpStatusCodeResult(HttpStatusCode.NoContent);
			}

			var stream = new MemoryStream();

			var spreadsheet = SpreadsheetDoreplacedent.Create(stream, SpreadsheetDoreplacedentType.Workbook);

			var workbookPart = spreadsheet.AddWorkbookPart();
			workbookPart.Workbook = new Workbook();

			var worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
			var sheet = new Sheet { Id = spreadsheet.WorkbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = viewName.Truncate(30) };

			var sheets = new Sheets();
			sheets.Append(sheet);

			var sheetData = new SheetData();

			var rowIndex = 1;
			var columnIndex = 1;

			var firstRow = new Row { RowIndex = (uint)rowIndex };

			var dataColumns = columns.Where(col => col.LogicalName != "col-action").ToArray();

			foreach (var column in dataColumns)
			{
				var cell = new Cell { CellReference = CreateCellReference(columnIndex) + rowIndex, DataType = CellValues.InlineString };

				var inlineString = new InlineString { Text = new Text { Text = column.Name } };

				cell.AppendChild(inlineString);

				firstRow.AppendChild(cell);

				columnIndex++;
			}

			sheetData.Append(firstRow);

			foreach (var record in data.Records)
			{
				var row = new Row { RowIndex = (uint)++rowIndex };

				columnIndex = 0;

				foreach (var column in dataColumns)
				{
					columnIndex++;

					var attribute = record.Attributes.FirstOrDefault(a => a.Name == column.LogicalName);

					if (attribute == null) continue;

					var isDateTime = attribute.AttributeMetadata.AttributeType == AttributeTypeCode.DateTime;

					var cell = new Cell { CellReference = CreateCellReference(columnIndex) + rowIndex, DataType = CellValues.InlineString };

					var inlineString = new InlineString { Text = new Text { Text = isDateTime ? this.GetFormattedDateTime(attribute, timezoneOffset) : attribute.DisplayValue as string } };

					cell.AppendChild(inlineString);

					row.AppendChild(cell);
				}

				sheetData.Append(row);
			}

			worksheetPart.Worksheet = new Worksheet(sheetData);

			spreadsheet.WorkbookPart.Workbook.AppendChild(sheets);

			workbookPart.Workbook.Save();

			spreadsheet.Close();

			var filename = new string(viewName.Where(c => !Path.GetInvalidFileNameChars().Contains(c)).ToArray());

			var sessionKey = "{0:s}|{1}.xlsx".FormatWith(DateTime.UtcNow, filename);

			stream.Position = 0; // Reset the stream to the beginning and save to session.

			Session[sessionKey] = stream;

			return Json(new { success = true, sessionKey }, JsonRequestBehavior.AllowGet);
		}

19 View Source File : EntityGridController.cs
License : MIT License
Project Creator : Adoxio

[HttpPost]
		[JsonHandlerError]
		[AjaxValidateAntiForgeryToken]
		public ActionResult DownloadAsCsv(string viewName, IEnumerable<LayoutColumn> columns, string base64SecureConfiguration, string sortExpression, string search, string filter,
			string metaFilter, int page = 1, int pageSize = DefaultPageSize)
		{
			var viewConfiguration = ConvertSecureStringToViewConfiguration(base64SecureConfiguration);
			using (PerformanceProfiler.Instance.StartMarker(PerformanceMarkerName.EnreplacedyGridController, PerformanceMarkerArea.Crm, PerformanceMarkerTagName.DownloadAsCsv))
			{
				if (viewConfiguration == null)
				{
					return new HttpStatusCodeResult(HttpStatusCode.Forbidden, ResourceManager.GetString("Invalid_Request"));
				}

				var dataAdapterDependencies = new PortalConfigurationDataAdapterDependencies(requestContext: Request.RequestContext, portalName: viewConfiguration.PortalName);
		
				// override the page parameters
				page = 1;
				pageSize = new SettingDataAdapter(dataAdapterDependencies, HttpContext.GetWebsite())
					.GetIntegerValue("Grid/Download/MaximumResults")
					.GetValueOrDefault(Fetch.MaximumPageSize);
				viewConfiguration.PageSize = pageSize;
			
				var json = GetData(viewConfiguration, sortExpression, search, filter, metaFilter, page, pageSize, true, false, null, null, null, null, true) as JsonResult;

				if (json == null)
				{
					return new HttpStatusCodeResult(HttpStatusCode.NoContent);
				}

				if (json.Data is EnreplacedyPermissionResult)
				{
					return json;
				}

				var data = json.Data as PaginatedGridData;

				if (data == null)
				{
					return new HttpStatusCodeResult(HttpStatusCode.NoContent);
				}

				var csv = new StringBuilder();

				var dataColumns = columns.Where(col => col.LogicalName != "col-action").ToArray();

				foreach (var column in dataColumns)
				{
					csv.Append(EncodeCommaSeperatedValue(column.Name));
				}

				csv.AppendLine();

				foreach (var record in data.Records)
				{
					foreach (var column in dataColumns)
					{
						var attribute = record.Attributes.FirstOrDefault(a => a.Name == column.LogicalName);

						if (attribute == null) continue;

						csv.Append(EncodeCommaSeperatedValue(attribute.DisplayValue as string));
					}

					csv.AppendLine();
				}

				var filename = new string(viewName.Where(c => !Path.GetInvalidFileNameChars().Contains(c)).ToArray());

				var sessionKey = "{0:s}|{1}.csv".FormatWith(DateTime.UtcNow, filename);

				Session[sessionKey] = csv.ToString();

				return Json(new { success = true, sessionKey }, JsonRequestBehavior.AllowGet);
			}
		}

19 View Source File : ValidFolderName.cs
License : MIT License
Project Creator : AiursoftWeb

public override bool IsValid(object value)
        {
            if (value is string val)
            {
                return
                    val.IndexOfAny(Path.GetInvalidFileNameChars()) < 0 &&
                    !string.IsNullOrWhiteSpace(val);
            }
            return false;
        }

19 View Source File : ValidFolderName.cs
License : MIT License
Project Creator : AiursoftWeb

protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if (IsValid(value))
            {
                return ValidationResult.Success;
            }
            else
            {
                if (string.IsNullOrWhiteSpace(value as string))
                {
                    return new ValidationResult($"Empty string is not a valid file name!");
                }

                var invalidCharacters = string.Empty;
                foreach (var invalidChar in Path.GetInvalidFileNameChars())
                {
                    if (value is string val && val.Contains(invalidChar))
                    {
                        invalidCharacters += $" '{invalidChar}',";
                    }
                }
                return new ValidationResult($"The {validationContext.DisplayName} can not contain invalid characters{invalidCharacters.TrimEnd(',')}!");
            }
        }

19 View Source File : Toolbox.cs
License : GNU General Public License v3.0
Project Creator : akaAgar

internal static string RemoveInvalidPathCharacters(string fileName)
        {
            if (string.IsNullOrEmpty(fileName)) return "_";
            return string.Join("_", fileName.Split(Path.GetInvalidFileNameChars()));
        }

19 View Source File : CommandLine.cs
License : GNU General Public License v3.0
Project Creator : akaAgar

private string RemoveInvalidPathCharacters(string fileName)
        {
            if (string.IsNullOrEmpty(fileName)) return "_";
            return string.Join("_", fileName.Split(Path.GetInvalidFileNameChars()));
        }

19 View Source File : FileIsExtensions.cs
License : MIT License
Project Creator : aljazsim

public static bool IsValidFileName(this string value)
        {
            if (value == null)
            {
                return true;
            }
            else if (string.IsNullOrWhiteSpace(value))
            {
                return false;
            }
            else
            {
                return !value.ToCharArray().Intersect(Path.GetInvalidFileNameChars()).Any();
            }
        }

19 View Source File : StringExtensions.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn

public static string AsFileName(this string input, bool throwExceptionOnInvalidCharacters = true)
        {
            if (string.IsNullOrWhiteSpace(input))
            {
                return input;
            }

            char[] illegalFileNameCharacters = System.IO.Path.GetInvalidFileNameChars();
            if (throwExceptionOnInvalidCharacters)
            {
                if (illegalFileNameCharacters.Any(ic => input.Any(i => ic == i)))
                {
                    throw new ArgumentOutOfRangeException(nameof(input));
                }

                return input;
            }

            return illegalFileNameCharacters.Aggregate(input, (current, c) => current.Replace(c, '_'));
        }

19 View Source File : StringExtensions.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn

public static string AsFileName(this string input, bool throwExceptionOnInvalidCharacters = true)
        {
            if (string.IsNullOrWhiteSpace(input))
            {
                return input;
            }

            char[] illegalFileNameCharacters = System.IO.Path.GetInvalidFileNameChars();
            if (throwExceptionOnInvalidCharacters)
            {
                if (illegalFileNameCharacters.Any(ic => input.Any(i => ic == i)))
                {                    
                    throw new ArgumentOutOfRangeException(nameof(input));
                }

                return input;
            }

            return illegalFileNameCharacters.Aggregate(input, (current, c) => current.Replace(c, '-'));
        }

19 View Source File : StringExtensions.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn

public static string AsFileName(this string input, bool throwExceptionOnInvalidCharacters = true)
        {
            if (string.IsNullOrWhiteSpace(input))
            {
                return input;
            }

            char[] illegalFileNameCharacters = Path.GetInvalidFileNameChars();
            if (throwExceptionOnInvalidCharacters)
            {
                if (illegalFileNameCharacters.Any(ic => input.Any(i => ic == i)))
                {
                    throw new ArgumentOutOfRangeException(nameof(input));
                }

                if (input == "..")
                {
                    throw new ArgumentOutOfRangeException(nameof(input));
                }

                return input;
            }

            if (input == "..")
            {
               return "-";
            }

            return illegalFileNameCharacters.Aggregate(input, (current, c) => current.Replace(c, '-'));
        }

19 View Source File : StringExtensions.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn

public static string AsFileName(this string input, bool throwExceptionOnInvalidCharacters = true)
        {
            if (string.IsNullOrWhiteSpace(input))
            {
                return input;
            }

            char[] illegalFileNameCharacters = Path.GetInvalidFileNameChars();
            if (throwExceptionOnInvalidCharacters)
            {
                if (illegalFileNameCharacters.Any(ic => input.Any(i => ic == i)))
                {
                    throw new ArgumentOutOfRangeException(nameof(input));
                }

                return input;
            }

            return illegalFileNameCharacters.Aggregate(input, (current, c) => current.Replace(c, '_'));
        }

19 View Source File : StringExtensions.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn

public static string AsFileName(this string input, bool throwExceptionOnInvalidCharacters = true)
        {
            if (string.IsNullOrWhiteSpace(input))
            {
                return input;
            }

            char[] illegalFileNameCharacters = System.IO.Path.GetInvalidFileNameChars();
            if (throwExceptionOnInvalidCharacters)
            {
                if (illegalFileNameCharacters.Any(ic => input.Any(i => ic == i)))
                {
                    throw new ArgumentOutOfRangeException(nameof(input));
                }

                if (input == "..")
                {
                    throw new ArgumentOutOfRangeException(nameof(input));
                }

                return input;
            }

            if (input == "..")
            {
               return "-";
            }

            return illegalFileNameCharacters.Aggregate(input, (current, c) => current.Replace(c, '-'));
        }

19 View Source File : StringExtensions.cs
License : GNU General Public License v3.0
Project Creator : alxnbl

public static string RemoveInvalidFileNameChars(this string filename)
        {
            return string.Concat(filename.Split(Path.GetInvalidFileNameChars()));
        }

19 View Source File : ModPacker.cs
License : GNU General Public License v3.0
Project Creator : AM2R-Community-Developers

private void CreateButton_Click(object sender, EventArgs e)
        {
            if (NameTextBox.Text == "" || AuthorTextBox.Text == "" || versionTextBox.Text == "")
            {
                MessageBox.Show("Text field missing! Mod packaging aborted.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (Path.GetInvalidFileNameChars().Any(NameTextBox.Text.Contains))
            {
                MessageBox.Show("Name contains invalid characters! These characters are not allowed:\n" + string.Join("\n", Path.GetInvalidFileNameChars()));
                return;
            }

            CreateLabel.Visible = true;
            CreateLabel.Text = "Packaging mod(s)... This could take a while!";

            string output;

            using (SaveFileDialog saveFile = new SaveFileDialog { RestoreDirectory = true, replacedle = "Save Windows mod profile", Filter = "zip files (*.zip)|*.zip", AddExtension = true })
            {
                if (saveFile.ShowDialog() == DialogResult.OK)
                {
                    output = saveFile.FileName;
                }
                else
                {
                    CreateLabel.Text = "Mod packaging aborted!";
                    return;
                }
            }

            CreateModPack("Windows", modPath, output);

            if (linuxCheckBox.Checked)
            {
                using (SaveFileDialog saveFile = new SaveFileDialog { RestoreDirectory = true, replacedle = "Save Linux mod profile", Filter = "zip files (*.zip)|*.zip", AddExtension = true })
                {
                    if (saveFile.ShowDialog() == DialogResult.OK)
                    {
                        output = saveFile.FileName;
                    }
                    else
                    {
                        CreateLabel.Text = "Mod packaging aborted!";
                        return;
                    }
                }

                CreateModPack("Linux", linuxPath, output);
            }

            CreateLabel.Text = "Mod package(s) created!";
        }

19 View Source File : Process.cs
License : MIT License
Project Creator : AmazingDM

private async void RemarkTextBox_TextChanged(object sender, EventArgs e)
        {
            await Task.Run(() =>
            {
                if (!UseCustomFilenameBox.Checked)
                {
                    var invalidFileChars = Path.GetInvalidFileNameChars();
                    var fileName = new StringBuilder(RemarkTextBox.Text);
                    foreach (var c in invalidFileChars)
                    {
                        fileName.Replace(c, '_');
                    }

                    FilenameTextBox.Text = fileName.ToString();
                }
            });
        }

19 View Source File : SongDownloader.cs
License : MIT License
Project Creator : andruzzzhka

private async Task ExtractZipAsync(Song songInfo, Stream zipStream, string customSongsPath)
        {
            try
            {
                Plugin.log.Debug("Extracting...");
                _extractingZip = true;
                ZipArchive archive = new ZipArchive(zipStream, ZipArchiveMode.Read);
                string basePath = songInfo.key + " (" + songInfo.songName + " - " + songInfo.levelAuthorName + ")";
                basePath = string.Join("", basePath.Split((Path.GetInvalidFileNameChars().Concat(Path.GetInvalidPathChars()).ToArray())));
                string path = customSongsPath + "/" + basePath;

                if (Directory.Exists(path))
                {
                    int pathNum = 1;
                    while (Directory.Exists(path + $" ({pathNum})")) ++pathNum;
                    path += $" ({pathNum})";
                }
                await Task.Run(() => archive.ExtractToDirectory(path)).ConfigureAwait(false);
                archive.Dispose();
                songInfo.path = path;
            }
            catch (Exception e)
            {
                Plugin.log.Critical($"Unable to extract ZIP! Exception: {e}");
                songInfo.songQueueState = SongQueueState.Error;
                _extractingZip = false;
                return;
            }
            zipStream.Close();

            if (string.IsNullOrEmpty(songInfo.path))
            {
                songInfo.path = customSongsPath;
            }

            _extractingZip = false;
            songInfo.songQueueState = SongQueueState.Downloaded;
            _alreadyDownloadedSongs.Add(songInfo);
            Plugin.log.Debug($"Extracted {songInfo.songName} {songInfo.songSubName}!");

        }

19 View Source File : Backup.cs
License : MIT License
Project Creator : ANF-Studios

public static void CreateBackup(in BackupOptions.BackupCreateOptions options)
        {
            // Seems like this method isn't effected unlike others.
            //if (options.BackupDirectory.Contains("-u") || options.BackupDirectory.Contains("-s"))
            //{
            //    Console.WriteLine("Whoops, seems like there's an error on our end. Please use --user (-u) and --system (-s) flags before --directory (-d).");
            //    return;
            //}

            if (!options.BackupUserVariables && !options.BackupSystemVariables)
            {
                Console.WriteLine("Did not modify any content because neither user or system flag is provided, exiting...");
                return;
            }

            // Invalid chars that may be in the provided directory.
            // For example:
            // When using a command argument `--directory "D:\backups\path\"` It takes the `\"` part
            // as a literal escape character which causes the value to be invalid.
            options.BackupDirectory = options.BackupDirectory.Trim(Path.GetInvalidFileNameChars());
            if (!options.BackupDirectory.EndsWith("\\") || !options.BackupDirectory.EndsWith("/"))
                options.BackupDirectory += "\\";

            string path = Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.User);
            string filename = DateTime.Now.ToFileTime().ToString();
            string finalPath = Path.Combine(options.BackupDirectory, filename);

            if (options.BackupSystemVariables)
                Console.WriteLine("System variables are not supported by the API.");
            else if (options.BackupUserVariables)
                Program.GetUserPath().BackupPath(
                    path,
                    filename,
                    options.BackupDirectory
                );
            if (File.Exists(finalPath))
                Console.WriteLine("Successfully backed up Path at: " + finalPath);
            else
                Console.WriteLine("Looks like something went wrong!");
        }

19 View Source File : Backup.cs
License : MIT License
Project Creator : ANF-Studios

public static void RemoveBackup(in BackupOptions.BackupRemoveOptions options)
        {
            // Seems like this not needed, but we're not sure just yet.
            //if (options.BackupDirectory.Contains("-n"))
            //{
            //    Console.WriteLine("Whoops, seems like there's an issue on our end. Please use the --name (-n) flag before --directory (-d).");
            //    return;
            //}

            // Invalid chars that may be in the provided directory.
            // For example:
            // When using a command argument `--directory "D:\backups\path\"` It takes the `\"` part
            // as a literal escape character which causes the value to be invalid.
            options.BackupDirectory = options.BackupDirectory.Trim(Path.GetInvalidFileNameChars());

            string file = Path.Combine(options.BackupDirectory, options.BackupFilename);
            try
            {
                File.Delete(file);
            }
            catch (DirectoryNotFoundException)
            {
                Console.WriteLine("`" + file + "` was not found!");
            }
            catch (Exception exception)
            {
                Console.WriteLine("Oh no, there was an error: " + exception.Message);
                Console.WriteLine("Please report to the developer.");
            }

            if (!File.Exists(file))
                Console.WriteLine("Successfully removed backup!");
            else
                Console.WriteLine("Could not remove " + file + "!");
        }

19 View Source File : Backup.cs
License : MIT License
Project Creator : ANF-Studios

public static void ApplyBackup(in BackupOptions.BackupApplyOptions options)
        {
            // Seems like this not needed, but we're not sure just yet.
            //if (options.BackupDirectory.Contains("-n"))
            //{
            //    Console.WriteLine("Whoops, seems like there's an issue on our end. Please use the --name (-n) flag before --directory (-d).");
            //    return;
            //}

            if (options.RestoreUserVariables && options.RestoreSystemVariables)
            {
                Console.WriteLine("Both user and system variables cannot be restored at the same time (this is to protect you).");
                return;
            }

            if (options.RestoreSystemVariables)
            {
                Console.WriteLine("System variables are not yet supported by the API.");
                return;
            }

            // Invalid chars that may be in the provided directory.
            // For example:
            // When using a command argument `--directory "D:\backups\path\"` It takes the `\"` part
            // as a literal escape character which causes the value to be invalid.
            options.BackupDirectory = options.BackupDirectory.Trim(Path.GetInvalidFileNameChars());

            string file = Path.Combine(options.BackupDirectory, options.BackupFilename);
            string initialUserPath = options.RestoreUserVariables
                                        ? Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.User)
                                        : null;
            string initialSystemPath = options.RestoreSystemVariables
                                        ? Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.Machine)
                                        : null;

            if (!File.Exists(file))
            {
                Console.WriteLine(file + " not found! Aborting restore.");
                return;
            }
            else
            {
                string newPath = File.ReadAllText(file);

                if (string.IsNullOrEmpty(newPath))
                {
                    Console.WriteLine("Given file is empty! Aborting restore.");
                    return;
                }

                if (options.RestoreUserVariables)
                {
                    string tempDir = Path.Combine(Path.GetTempPath(), "WinPath");

                    try
                    {
                        if (!Directory.Exists(tempDir))
                            Directory.CreateDirectory(tempDir);
                        File.WriteAllText(userinitialBackup, initialUserPath);
                    }
                    catch (UnauthorizedAccessException) { Console.WriteLine("Whoops, we do not have enough permissions to create a backup before replacing, it's okay though!"); }
                    catch (Exception exception) { Console.WriteLine("There seems to be an error backing up the path before replacing, it's okay though!\nDetails: " + exception.Message); }

                    Environment.SetEnvironmentVariable("Path", newPath, EnvironmentVariableTarget.User);

                    Console.WriteLine("Successfully restored file as new Path!");
                    Console.WriteLine("In case if you changed your mind, there is a backup at: " + userinitialBackup);
                }
                if (options.RestoreSystemVariables)
                {
                    File.WriteAllText(systeminitialBackup, initialSystemPath);

                    Environment.SetEnvironmentVariable("Path", newPath, EnvironmentVariableTarget.Machine);

                    Console.WriteLine("Successfully restored file as new Path!");
                    Console.WriteLine("In case if you changed your mind, there is a backup at: " + systeminitialBackup);
                }
            }
        }

19 View Source File : EnmityInfoWorker.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta

private async void WriteEnmityLog(
            IEnumerable<EnmityEntry> enmityEntryList)
        {
            var config = Settings.Instance.Enmity;

            if (string.IsNullOrEmpty(config.LogDirectory))
            {
                return;
            }

            var player = CombatantsManager.Instance.Player;
            if (player == null)
            {
                return;
            }

#if !DEBUG
            if (SharlayanHelper.Instance.PartyMemberCount < 4)
            {
                return;
            }
#endif

            if (enmityEntryList.Count() < 1)
            {
                return;
            }

            if (!Directory.Exists(config.LogDirectory))
            {
                Directory.CreateDirectory(config.LogDirectory);
            }

            var now = DateTime.Now;

            await Task.Run(() =>
            {
                lock (LogLocker)
                {
                    var inCombat = XIVPluginHelper.Instance.InCombat;
                    if (this.currentInCombat != inCombat)
                    {
                        this.currentInCombat = inCombat;

                        if (this.currentInCombat)
                        {
                            this.currentTake++;
                        }
                        else
                        {
                            this.logStream?.Flush();
                        }
                    }

                    var zone = ActGlobals.oFormActMain.CurrentZone;
                    if (this.currentZone != zone)
                    {
                        this.currentZone = zone;
                        this.logStream?.Flush();
                    }

                    var f = $"{now:yyyy-MM-dd}.Enmity.{zone}.take{this.currentTake}.csv";
                    f = string.Concat(f.Where(c => !Path.GetInvalidFileNameChars().Contains(c)));

                    var fileName = Path.Combine(
                        config.LogDirectory,
                        f);

                    if (string.IsNullOrEmpty(this.currentLogFile) ||
                        this.currentLogFile != fileName)
                    {
                        this.currentLogFile = fileName;

                        if (this.logStream != null)
                        {
                            this.logStream.Flush();
                            this.logStream.Close();
                            this.logStream = null;
                        }

                        this.logStream = new StreamWriter(
                            this.currentLogFile,
                            false,
                            new UTF8Encoding(false));
                    }

                    if (this.logStream != null)
                    {
                        var fields = new List<string>(24);

                        fields.Add(now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
                        fields.Add("\"" + this.TargetInfo.Name + "\"");

                        var party = CombatantsManager.Instance.GetPartyList();

                        foreach (var member in party)
                        {
                            Thread.Yield();

                            var enmityData = enmityEntryList.FirstOrDefault(x =>
                                x.ID == member.ID);

                            fields.Add("\"" + member.Name + "\"");
                            fields.Add("\"" + member.JobID.ToString() + "\"");
                            fields.Add((enmityData?.Enmity ?? 0).ToString("#"));
                        }

                        this.logStream.WriteLine(string.Join(",", fields));
                    }
                }
            });
        }

19 View Source File : XIVAPIController.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta

public async Task DownloadActionIcons(
            string saveDirectory,
            IEnumerable<ActionModel> actions,
            ProgressDownloadCallbak callback = null)
        {
            // ファイル名に使えない文字を取得しておく
            var invalidChars = Path.GetInvalidFileNameChars();

            var iconBaseDirectory = Path.Combine(
                saveDirectory,
                "Action icons");

            var iconBaseDirectoryBack = iconBaseDirectory + ".back";
            if (Directory.Exists(iconBaseDirectory))
            {
                if (Directory.Exists(iconBaseDirectoryBack))
                {
                    Directory.Delete(iconBaseDirectoryBack, true);
                }

                Directory.Move(iconBaseDirectory, iconBaseDirectoryBack);
            }

            var i = 1;
            var jobIDs = Jobs.PopularJobIDs
                .Select(x => new
                {
                    No = i++,
                    ID = x,
                    Name = Jobs.Find(x)?.NameEN
                });

            using (var wc = new WebClient())
            {
                foreach (var jobID in jobIDs)
                {
                    var actionsByJob =
                        from x in actions
                        where
                        x.ContainsJob(jobID.ID)
                        group x by
                        x.Name;

                    var dirName = $"{jobID.No:00}_{jobID.Name}";
                    var dir = Path.Combine(iconBaseDirectory, dirName);
                    if (!Directory.Exists(dir))
                    {
                        Directory.CreateDirectory(dir);
                    }

                    var current = 1;
                    foreach (var group in actionsByJob)
                    {
                        var action = group.First();

                        var fileName = $"{(action.ID ?? 0):0000}_{action.Name}.png";

                        // ファイル名に使えない文字を除去する
                        fileName = string.Concat(fileName.Where(c =>
                            !invalidChars.Contains(c)));

                        var file = Path.Combine(dir, fileName);
                        if (File.Exists(file))
                        {
                            File.Delete(file);
                        }

                        var uri = BaseAddress.ToString() + "/" + action.Icon;
                        await wc.DownloadFileTaskAsync(uri, file);

                        if (callback != null)
                        {
                            callback.Invoke(new DownloadProgressEventArgs()
                            {
                                Current = current,
                                Max = actionsByJob.Count(),
                                CurrentObject = Path.Combine(dirName, fileName),
                            });
                        }

                        current++;
                        await Task.Delay(1);
                    }
                }
            }

            if (Directory.Exists(iconBaseDirectoryBack))
            {
                Directory.Delete(iconBaseDirectoryBack, true);
            }
        }

19 View Source File : ActionEchoesModel.cs
License : MIT License
Project Creator : anoyetta-academy

public async Task SaveLogAsync()
        {
            if (this.echoes.Count < 1)
            {
                return;
            }

            var fileName = string.Empty;

            lock (this)
            {
                var encounter = ActGlobals.oFormActMain?.ActiveZone?.ActiveEncounter;
                var zone = !string.IsNullOrEmpty(encounter?.ZoneName) ?
                    encounter?.ZoneName :
                    this.Zone;
                var replacedle = !string.IsNullOrEmpty(encounter?.replacedle) ?
                    encounter?.replacedle :
                    "UNKNOWN";

                fileName =
                    $"{DateTime.Now:yyMMdd_HHmmss}_{this.PlayerName}[{this.PlayerJob}]_{zone}({replacedle}).json";

                // 無効な文字を取り除く
                fileName = string.Concat(fileName.Where(c => !Path.GetInvalidFileNameChars().Contains(c)));
            }

            if (string.IsNullOrEmpty(this.Config.LogDirectory))
            {
                return;
            }

            await Task.Run(async () =>
            {
                if (!Directory.Exists(this.Config.LogDirectory))
                {
                    Directory.CreateDirectory(this.Config.LogDirectory);
                }

                var f = Path.Combine(this.Config.LogDirectory, fileName);

                try
                {
                    this.toFile = true;

                    File.WriteAllText(
                        f,
                        await this.ParseJsonAsync(),
                        new UTF8Encoding(false));
                }
                finally
                {
                    this.toFile = false;
                }
            });
        }

19 View Source File : FileUtils.cs
License : MIT License
Project Creator : AntonyCorbett

public static string CoerceValidFileName(string filename)
        {
            var invalidChars = Regex.Escape(new string(Path.GetInvalidFileNameChars()));
            var invalidReStr = [email protected]"[{invalidChars}]+";

            var reservedWords = new[]
            {
                "CON", "PRN", "AUX", "CLOCK$", "NUL", "COM0", "COM1", "COM2", "COM3", "COM4",
                "COM5", "COM6", "COM7", "COM8", "COM9", "LPT0", "LPT1", "LPT2", "LPT3", "LPT4",
                "LPT5", "LPT6", "LPT7", "LPT8", "LPT9",
            };

            var sanitisedNamePart = Regex.Replace(filename, invalidReStr, "_");
            foreach (var reservedWord in reservedWords)
            {
                var reservedWordPattern = $"^{reservedWord}\\.";
                sanitisedNamePart = Regex.Replace(sanitisedNamePart, reservedWordPattern, "_reservedWord_.", RegexOptions.IgnoreCase);
            }

            return sanitisedNamePart;
        }

19 View Source File : FileUtils.cs
License : MIT License
Project Creator : AntonyCorbett

public static string CleanFileName(string filename)
        {
            return Path.GetInvalidFileNameChars().Aggregate(filename, (current, c) =>
                current.Replace(c.ToString(CultureInfo.InvariantCulture), string.Empty));
        }

19 View Source File : StoredAIs.cs
License : GNU Lesser General Public License v3.0
Project Creator : ApexGameTools

internal static string EnsureValidName(string name, AIStorage target)
        {
            if (string.IsNullOrEmpty(name))
            {
                name = "New AI";
            }
            else
            {
                var invalidChars = System.IO.Path.GetInvalidFileNameChars();
                var transformer = new StringBuilder(name.Length);
                for (int i = 0; i < name.Length; i++)
                {
                    var allowChar = true;
                    for (int j = 0; j < invalidChars.Length; j++)
                    {
                        var invalidChar = invalidChars[j];
                        if (invalidChar.Equals(name[i]))
                        {
                            allowChar = false;
                            break;
                        }
                    }

                    if (allowChar)
                    {
                        transformer.Append(name[i]);
                    }
                }

                name = transformer.ToString();
            }

            var nameBase = name;
            int idx = 0;
            var stored = AIs.FirstOrDefault(a => a.name.Equals(name, StringComparison.OrdinalIgnoreCase));
            while (stored != null && !object.ReferenceEquals(stored, target))
            {
                idx++;
                name = string.Concat(nameBase, " ", idx.ToString("##"));
                stored = AIs.FirstOrDefault(a => a.name.Equals(name, StringComparison.OrdinalIgnoreCase));
            }

            return name;
        }

19 View Source File : PathUtils.cs
License : MIT License
Project Creator : aprilyush

private static char[] GetInvalidChars()
        {
            return Path.GetInvalidFileNameChars().Concat(Path.GetInvalidPathChars()).Concat(new[] { ' ', ';' }).ToArray();
        }

19 View Source File : Extensions.cs
License : GNU Affero General Public License v3.0
Project Creator : arklumpus

public static string CoerceValidFileName(this string filename)
        {
            var invalidChars = Regex.Escape(new string(System.IO.Path.GetInvalidFileNameChars()));
            var invalidReStr = string.Format(@"[{0}]+", invalidChars);

            var reservedWords = new[]
            {
                "CON", "PRN", "AUX", "CLOCK$", "NUL", "COM0", "COM1", "COM2", "COM3", "COM4",
                "COM5", "COM6", "COM7", "COM8", "COM9", "LPT0", "LPT1", "LPT2", "LPT3", "LPT4",
                "LPT5", "LPT6", "LPT7", "LPT8", "LPT9"
            };

            var sanitisedNamePart = Regex.Replace(filename, invalidReStr, "_");
            foreach (var reservedWord in reservedWords)
            {
                var reservedWordPattern = string.Format("^{0}\\.", reservedWord);
                sanitisedNamePart = Regex.Replace(sanitisedNamePart, reservedWordPattern, "_reservedWord_.", RegexOptions.IgnoreCase);
            }

            return sanitisedNamePart;
        }

19 View Source File : LanguageManager.cs
License : MIT License
Project Creator : Asixa

public void LoadLanguage(string pack)
        {
           // CultureInfo currentCultureInfo = CultureInfo.CurrentCulture;

            ResourceDictionary langRd = null;
              try
             {
            string path = "/Languages/" + pack + ".xaml";
            langRd =Application.LoadComponent(new Uri(@path,UriKind.Relative)) as ResourceDictionary;
            }
            catch{
                char[] InvaildChar = Path.GetInvalidFileNameChars();
                if (InvaildChar.Length>0)
                 {
                 //含有非法字符 \ / : * ? " < > | 等
                MessageBox. Show(@"Language pack cannot be loaded "+Environment.NewLine+ @" becasue he path contains illegal character" + Environment.NewLine + @"(\ / : * ? !@ # ¥ %……&*())..."
                    + "\n" + new Uri(Environment.CurrentDirectory + "/Languages/" + pack + ".xaml", UriKind.Absolute).ToString()
                , "Error" , MessageBoxButton.OK, MessageBoxImage.Error);
      }
            }

            if (langRd != null)
            {
                if (MainWindow._instance.Resources.MergedDictionaries.Count > 0)
                {
                    MainWindow._instance.Resources.MergedDictionaries.Clear();
                }
                MainWindow._instance.Resources.MergedDictionaries.Add(langRd);

                if (MainWindow._instance.LoginWindow.Resources.MergedDictionaries.Count > 0)
                {
                    MainWindow._instance.LoginWindow.Resources.MergedDictionaries.Clear();
                }
                MainWindow._instance.LoginWindow.Resources.MergedDictionaries.Add(langRd);

                if (MainWindow._instance.LoginWindow.Resources.MergedDictionaries.Count > 0)
                {
                    MainWindow._instance.LoginWindow.Resources.MergedDictionaries.Clear();
                }
                MainWindow._instance.LoginWindow.Resources.MergedDictionaries.Add(langRd);

                if (MainWindow._instance.output_window.Resources.MergedDictionaries.Count > 0)
                {
                    MainWindow._instance.output_window.Resources.MergedDictionaries.Clear();
                }
                MainWindow._instance.output_window.Resources.MergedDictionaries.Add(langRd);

                if (MainWindow._instance.option_window.Resources.MergedDictionaries.Count > 0)
                {
                    MainWindow._instance.option_window.Resources.MergedDictionaries.Clear();
                }
                MainWindow._instance.option_window.Resources.MergedDictionaries.Add(langRd);

                if (MainWindow._instance.option_window.detail.Resources.MergedDictionaries.Count > 0)
                {
                    MainWindow._instance.option_window.detail.Resources.MergedDictionaries.Clear();
                }
                MainWindow._instance.option_window.detail.Resources.MergedDictionaries.Add(langRd);

            }
        }

19 View Source File : UserSecretsConfigBuilder.cs
License : MIT License
Project Creator : aspnet

private string GetSecretsFileFromId(string secretsId)
        {
            // The common VS scenario will leave this Id attribute empty, or as a place-holding token. In that case,
            // go look up the user secrets id from the magic file.
            if (String.IsNullOrWhiteSpace(secretsId) || secretsId.Equals("${UserSecretsId}", StringComparison.InvariantCultureIgnoreCase))
            {
                // The magic file should be deployed in our codebase
                string codebase = System.Reflection.replacedembly.GetExecutingreplacedembly().CodeBase;
                string localpath = new Uri(codebase).LocalPath;
                string magicId = File.ReadAllText(localpath + ".UserSecretsId.txt");

                if (!String.IsNullOrWhiteSpace(magicId))
                {
                    secretsId = magicId.Trim();
                }
            }

            // Make sure the identifier is legal for file paths.
            int badCharIndex = secretsId.IndexOfAny(Path.GetInvalidFileNameChars());
            if (badCharIndex != -1)
            {
                throw new InvalidOperationException($"Invalid character '{secretsId[badCharIndex]}' in '{userSecretsIdTag}'.");
            }

            // Try Windows-style first
            string root = Environment.GetEnvironmentVariable("APPDATA");
            if (!String.IsNullOrWhiteSpace(root))
                return Path.Combine(root, "Microsoft", "UserSecrets", secretsId, "secrets.xml");

            // Then try unix-style
            root = Environment.GetEnvironmentVariable("HOME");
            if (!String.IsNullOrWhiteSpace(root))
                return Path.Combine(root, ".microsoft", "usersecrets", secretsId, "secrets.xml");

            return null;
        }

19 View Source File : AMLUtils.cs
License : MIT License
Project Creator : AstroTechies

public static string SanitizeFilename(string name)
        {
            string invalidCharactersRegex = string.Format(@"([{0}]*\.+$)|([{0}]+)", Regex.Escape(new string(Path.GetInvalidFileNameChars())));
            return Regex.Replace(name, invalidCharactersRegex, "_");
        }

19 View Source File : WalletNameViewModel.cs
License : GNU General Public License v3.0
Project Creator : atomex-me

public override void Next()
        {
            if (string.IsNullOrEmpty(WalletName)) {
                Warning = Resources.CwvEmptyWalletName;
                return;
            }

            if (WalletName.IndexOfAny(Path.GetInvalidFileNameChars()) != -1 ||
                WalletName.IndexOf('.') != -1) {
                Warning = Resources.CwvInvalidWalletName;
                return;
            }

            var pathToWallet = $"{WalletInfo.CurrentWalletDirectory}/{WalletName}/{WalletInfo.DefaultWalletFileName}";

            try
            {
                var _ = Path.GetFullPath(pathToWallet);
            }
            catch (Exception)
            {
                Warning = Resources.CwvInvalidWalletName;
                return;
            }

            if (File.Exists(pathToWallet)) {
                Warning = Resources.CwvWalletAlreadyExists;
                return;
            }

            StepData.PathToWallet = pathToWallet;

            RaiseOnNext(StepData);
        }

19 View Source File : PageContext.cs
License : Microsoft Public License
Project Creator : atrenton

internal void SaveCurrentPageToDisk()
        {
            var fileName = PageName;
            var invalidCharList = Path.GetInvalidFileNameChars().ToList<char>();
            invalidCharList.ForEach(ch => fileName = fileName.Replace(ch, '-'));

            var desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            var dir = Path.Combine(desktop, "MyJournal");
            if (!Directory.Exists(dir)) Directory.CreateDirectory(dir);

            var filePath = Path.Combine(dir, fileName + ".xml");
            Tracer.WriteTraceMethodLine("FilePath = {0}", filePath);

            using (var fs = new FileStream(filePath, FileMode.Create))
            {
                _CurrentPage.Save(fs);
            }
        }

19 View Source File : FileUtility.cs
License : GNU General Public License v3.0
Project Creator : autodotua

private static string GetValidFileName(string name)
        {
            foreach (char c in P.GetInvalidFileNameChars())
            {
                name = name.Replace(c, '_');
            }
            return name;
        }

19 View Source File : FileBlogService.cs
License : Apache License 2.0
Project Creator : aws

private static string CleanFromInvalidChars(string input)
        {
            // ToDo: what we are doing here if we switch the blog from windows to unix system or
            // vice versa? we should remove all invalid chars for both systems

            var regexSearch = Regex.Escape(new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars()));
            var r = new Regex($"[{regexSearch}]");
            return r.Replace(input, string.Empty);
        }

19 View Source File : frmRename.cs
License : MIT License
Project Creator : AyrA

private void SetBtn()
        {
            var BaseState = true;
            if (BaseState && string.IsNullOrWhiteSpace(tbSessionName.Text))
            {
                BaseState = false;
            }
            if (BaseState && string.IsNullOrWhiteSpace(tbFileName.Text))
            {
                BaseState = false;
            }
            if (BaseState && Path.GetInvalidFileNameChars().Any(m => tbSessionName.Text.Contains(m)))
            {
                BaseState = false;
            }
            if (BaseState && Path.GetInvalidFileNameChars().Any(m => tbFileName.Text.Contains(m)))
            {
                BaseState = false;
            }
            if (btnOK.Enabled != BaseState)
            {
                btnOK.Enabled = BaseState;
            }
        }

19 View Source File : FileUtils.cs
License : GNU General Public License v3.0
Project Creator : az64

public static string MakeFilenameValid(string filename)
        {
            foreach (var c in Path.GetInvalidFileNameChars()) { filename = filename.Replace(c, '-'); }
            return filename;
        }

19 View Source File : EntityInvoker.cs
License : MIT License
Project Creator : Azure

private void Validate()
        {
            if (this._entryPointDefinitionAttribute != null)
            {
                string id = this._entryPointDefinitionAttribute.Id;
                if (string.IsNullOrWhiteSpace(id))
                {
                    throw new ScriptCompilationException("Id cannot be empty in Definition attribute");
                }

                if (string.IsNullOrWhiteSpace(this._entryPointDefinitionAttribute.Name))
                {
                    throw new ScriptCompilationException("Name cannot be empty in Definition attribute");
                }

                // Validate empty author
                if (string.IsNullOrWhiteSpace(this._entryPointDefinitionAttribute.Author))
                {
                    throw new ScriptCompilationException("Author not specified in Definition attribute");
                }

                List<char> invalidChars = Path.GetInvalidFileNameChars().ToList();
                invalidChars.ForEach(x =>
                {
                    if (id.Contains(x))
                    {
                        throw new ScriptCompilationException($"Id(in Definition attribute) cannot contain illegal character : {x}");
                    }

                    if (this._entryPointDefinitionAttribute.Author.Contains(x))
                    {
                        throw new ScriptCompilationException($"Author(in Definition attribute) cannot contain illegal character : {x}");
                    }
                });

                // Validate Support Topic Attributes
                if (this._entryPointDefinitionAttribute.SupportTopicList != null)
                {
                    this._entryPointDefinitionAttribute.SupportTopicList.ToList().ForEach(item =>
                    {
                        if (string.IsNullOrWhiteSpace(item.Id))
                        {
                            throw new ScriptCompilationException("Missing Id from Support Topic Attribute");
                        }

                        if (string.IsNullOrWhiteSpace(item.PesId))
                        {
                            throw new ScriptCompilationException("Missing PesId from Support Topic Attribute");
                        }
                    });

                    if (this._systemFilter == null && this._resourceFilter.InternalOnly && this._entryPointDefinitionAttribute.SupportTopicList.Any())
                    {
                        this.CompilationOutput = this.CompilationOutput.Concat(new string[] { "WARNING: Detector is marked internal and SupportTopic is specified. This means the detector will be enabled for Azure Support Center but not for case submission flow, until the isInternal flag is set to false." });
                        this.DetailedCompilationTraces = this.DetailedCompilationTraces.Concat(CompilationTraceOutputDetails.GetCompilationTraceDetailsList(new string[] { "WARNING: Detector is marked internal and SupportTopic is specified. This means the detector will be enabled for Azure Support Center but not for case submission flow, until the isInternal flag is set to false." }));
                    }

                    if(this._resourceFilter is ArmResourceFilter armResFilter)
                    {
                        // For sharable Gists, validate the provider and resource type configuration is correct
                        if (this._enreplacedyMetaData.Type == EnreplacedyType.Gist && armResFilter.Provider == "*" && armResFilter.ResourceTypeName != "*")
                        {
                            this.CompilationOutput = this.CompilationOutput.Concat(new string[]
                            {
                                "ERROR: Invalid ARM Resource Filter values. Provider cannot be '*' when ResourceTypeName is not '*'",
                                "Valid Options:",
                                "- [ArmResourceFilter(provider: \"*\", resourceTypeName: \"*\")]",
                                "- [ArmResourceFilter(provider: \"Microsoft.YourProviderName\", resourceTypeName: \"*\")]",
                                "- [ArmResourceFilter(provider: \"Microsoft.YourProviderName\", resourceTypeName: \"Microsoft.YourResourceTypeName\")]"
                            });

                            this.DetailedCompilationTraces = this.DetailedCompilationTraces.Concat(CompilationTraceOutputDetails.GetCompilationTraceDetailsList(new string[] {
                                @"ERROR: Invalid ARM Resource Filter values. Provider cannot be '*' when ResourceTypeName is not '*'
                                Valid Options:,
                                - [ArmResourceFilter(provider: ""*"", resourceTypeName: ""*"")],
                                - [ArmResourceFilter(provider: ""Microsoft.YourProviderName"", resourceTypeName: ""*"")],
                                - [ArmResourceFilter(provider: ""Microsoft.YourProviderName"", resourceTypeName: ""Microsoft.YourResourceTypeName"")]"
                            }));

                            throw new ScriptCompilationException(string.Empty);
                        }
                        // Sharable detectors are not supported as of now.
                        else if(this._enreplacedyMetaData.Type != EnreplacedyType.Gist && (armResFilter.Provider == "*" || armResFilter.ResourceTypeName == "*"))
                        {
                            this.CompilationOutput = this.CompilationOutput.Concat(new string[] 
                            {
                                "ERROR : Invalid character '*' in ARM Resource Filter. Sharable detectors are not supported as of now.",
                                "Valid Options:",
                                "- [ArmResourceFilter(provider: \"Microsoft.YourProviderName\", resourceTypeName: \"Microsoft.YourResourceTypeName\")]"
                            });

                            this.DetailedCompilationTraces = this.DetailedCompilationTraces.Concat(CompilationTraceOutputDetails.GetCompilationTraceDetailsList(new string[] {
                                @"ERROR: Invalid character '*' in ARM Resource Filter. Sharable detectors are not supported as of now.
                                Valid Options:,
                                - [ArmResourceFilter(provider: ""Microsoft.YourProviderName"", resourceTypeName: ""Microsoft.YourResourceTypeName"")]"
                            }));

                            throw new ScriptCompilationException(string.Empty);
                        }
                    }
                }

                if (this._systemFilter != null && this._resourceFilter != null)
                {
                    throw new ScriptCompilationException("Detector is marked with both SystemFilter and ResourceFilter. System Invoker should not include any ResourceFilter attribute.");
                }

                if((this._enreplacedyMetaData.ScriptText.Contains("All('") || this._enreplacedyMetaData.ScriptText.Contains("All(\"")) && 
                    (this._resourceFilter.ResourceType == ResourceType.App 
                    || this._resourceFilter.ResourceType == ResourceType.HostingEnvironment 
                    || this._resourceFilter.ResourceType == ResourceType.AppServiceCertificate
                    || this._resourceFilter.ResourceType == ResourceType.AppServiceDomain))
                {
                    this.CompilationOutput = this.CompilationOutput.Concat(new string[]
                           {
                                "ERROR : Use of All('TableName') kusto function is not supported.",
                                "Valid Options:",
                                "- Use dp.Kusto.ExecuteQueryOnAllAppAppServiceClusters(string query, string operationName) instead."
                           });

                    this.DetailedCompilationTraces = this.DetailedCompilationTraces.Concat(CompilationTraceOutputDetails.GetCompilationTraceDetailsList(new string[] {
                                @"ERROR: Use of All('TableName') kusto function is not supported.
                                Valid Options:,
                                - Use dp.Kusto.ExecuteQueryOnAllAppAppServiceClusters(string query, string operationName) instead."
                            }));
                    throw new ScriptCompilationException("Use of All('TableName') in kusto query is not allowed. Use dp.Kusto.ExecuteQueryOnAllAppAppServiceClusters instead.");
                }
            }
        }

19 View Source File : CdmMessageProcessor.cs
License : MIT License
Project Creator : Azure

private string GetNormalizedKey(string key) {
            key = string.Join("", key.Split(Path.GetInvalidFileNameChars()));
            return key.Replace('#', '_').Replace('.', '_')
                .Replace('/', '_').Replace(':', '_')
                .Replace('"', '_').Replace('\'', '_')
                .Replace('\\', '_');
        }

See More Examples