if (sanitizedProgramName.Length > allowedLength)
sanitizedProgramName = sanitizedProgramName.Substring(0, allowedLength);
return $"{CommonConstants.NameFormatForPdfFileNamePrefix}{sanitizedProgramName}-{DateTime.UtcNow.ToString(CommonConstants.DateFormatForPdfFileNameSuffix)}";
}
ye constant variables:
public static readonly string NameFormatForPdfFileNamePrefix = "FD-Program-Performance-";
public static readonly string DateFormatForPdfFileNameSuffix = "MMddyyyyHHmmss";
mera issue ye h ki mujhe jab pdf download ho tab uska filename ka format proper aana chahiye jisme max length 150 m cover hojaaye.
uske liye sanitize method likhi h or special characters remove krna h or blankspace ko replace _ isse
but proper work nhi krrha.
filenotfound ki error aati h .
resolve it
Assistant
आपके code में कुछ issues हैं जो FileNotFound error का कारण बन रहे हैं। Main problems ये हैं:
Spaces को underscores से replace नहीं हो रहा
कुछ special characters अभी भी allowed pattern में included हैं
File name में अभी भी invalid characters हो सकते हैं
यहाँ है fixed version:
csharp
public static class FileNameHelper
{
public static string SanitizeFileName(string inputValue)
{
try
{
if (string.IsNullOrWhiteSpace(inputValue))
return string.Empty;
// Remove control characters first (like \r, \n, \u0001 etc.)
inputValue = new string(inputValue.Where(ch => !char.IsControl(ch)).ToArray());
// Replace spaces with underscores
inputValue = inputValue.Replace(" ", "_");
// Remove all Windows-invalid characters and other problematic characters
inputValue = Regex.Replace(inputValue, @"[<>:\""\/\\|?*]", "");
// Extract extension first
string fileExtension = GetExtension(inputValue);
string fileNameWithoutExtension = GetFileNameWithoutExtension(inputValue);
// Keep only safe characters (letters, numbers, underscore, hyphen, dot)
string allowedPattern = @"[^a-zA-Z0-9\-_\.]";
string sanitizedFileName = Regex.Replace(fileNameWithoutExtension, allowedPattern, "");
// Clean up dots and trim
sanitizedFileName = sanitizedFileName.TrimStart('.').TrimEnd('.').Trim('_');
// Ensure filename is not empty
if (string.IsNullOrEmpty(sanitizedFileName))
sanitizedFileName = "file";
// Reattach extension if exists
if (!string.IsNullOrEmpty(fileExtension))
{
sanitizedFileName += "." + fileExtension.TrimStart('.').Replace(".", "");
}
return sanitizedFileName;
}
catch
{
return "file"; // Return safe default instead of original input
}
}
private static string GetExtension(string path)
{
if (string.IsNullOrWhiteSpace(path))
return string.Empty;
int i = path.LastIndexOf('.');
if (i >= 0 && i < path.Length - 1)
{
return path.Substring(i);
}
return string.Empty;
}
private static string GetFileNameWithoutExtension(string path)
{
if (string.IsNullOrWhiteSpace(path))
return string.Empty;
int slash = path.LastIndexOfAny(new[] { '/', '\\' });
int dot = path.LastIndexOf('.');
if (dot > slash)
{
return path.Substring(slash + 1, dot - slash - 1);
}
return path.Substring(slash + 1);
}
}