FormatException int.Parse() even when passing correct format string value

0

I am trying to initialize the appsettings to FileUploadSetting object through startup using AddSingleton DI. Even though the value passed to int.Parse() method in different property just to access the converted value of AllowedFileSize is "3145728‬" then also it gives error as FormatException. What i am doing wrong ?

appsettings.json

"FileUploadSetting": {
    "AllowedExtensions": [ ".pdf", ".doc", ".docx" ],
    "StoredFilesPath": "Uploads/",
    "AllowedFileSize": "3145728‬" //in bytes

  },

Startup.cs

//FileUploadSetting
services.AddSingleton<WebApplication.Services.FileUpload.IFileUploadSetting>(Configuration.GetSection("FileUploadSetting").Get<WebApplication.Services.FileUpload.FileUploadSetting>());

FileUploadSetting.cs

public interface IFileUploadSetting
    {
        string[] AllowedExtensions { get; set; }
        string StoredFilesPath { get; set; }
        string AllowedFileSize { get; set; }
        int GetAllowedFileSize { get;}
    }
public class FileUploadSetting : IFileUploadSetting
    {
        public string[] AllowedExtensions { get; set; }
        public string StoredFilesPath { get; set; }
        public string AllowedFileSize { get; set; }

        public int GetAllowedFileSize
        {
            get
            {
                return int.Parse(AllowedFileSize);//**Error mention below even though when breakpoint is placed the value passed to it is "3145728‬"**
            }

        }
    }

Error

System.FormatException
  HResult=0x80131537
  Message=Input string was not in a correct format.
  Source=System.Private.CoreLib
  StackTrace:
   at System.Number.ThrowOverflowOrFormatException(ParsingStatus status, TypeCode type)
   at System.Number.ParseInt32(ReadOnlySpan`1 value, NumberStyles styles, NumberFormatInfo info)
   at System.Int32.Parse(String s)
   at Clanstech.Services.FileUpload.FileUploadSetting.get_GetAllowedFileSize() in C:\Users\admin\source\Workspaces\WebApplication\Services\FileUpload\FileUploadSetting.cs:line 18

Screenshot For Reference

c#
asp.net-core
properties
startup
appsettings
asked on Stack Overflow May 13, 2020 by Anuj Chauhan

1 Answer

1

You have an invisible character at the end (after the 8).

You'll notice that the following evaluates to true:

AllowedFileSize[7] == '\u202c'

One approach could be

return int.Parse(AllowedFileSize.Trim('\u202c'));  

But that's just a "quick" fix, and you'll likely just want to fix the json. Delete the whole value, including the double quotes and re-type those as well.
Your editor probably won't capture that hidden character if you do something like double click the value to edit (Visual Studio didn't when I tested this).

answered on Stack Overflow May 13, 2020 by Broots Waymb • edited May 13, 2020 by Broots Waymb

User contributions licensed under CC BY-SA 3.0