简体   繁体   中英

c# reading csv file System.Security.SecurityException

I need to read a csv file in my webservice,

here is my code so far :

[WebMethod]
    public List<string> getIdentifiants()
    {
        List<string> listA = new List<string>();
        List<string> listB = new List<string>();
        using (var fs = File.OpenRead(@"C:\Users\stag01\Desktop\identifiants.csv"))
        using (var reader = new StreamReader(fs))
        {

            while (!reader.EndOfStream)
            {
                var line = reader.ReadLine();
                var values = line.Split(';');

                listA.Add(values[0]);
                listB.Add(values[1]);
            }
        }

        return listA;

    }

But when I try to run it, I got this error :

System.Security.SecurityException: Échec de la demande d'autorisation de type 'System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.
à System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet)
à System.Security.CodeAccessPermission.Demand()
à System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)
à System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share)
à System.IO.File.OpenRead(String path)
à WebApplication1.WS_stage_2017.getIdentifiants() dans \\Nas-server\\User Folder\\stag01\\Mes documents\\Visual Studio 2017\\Projects\\WebApplication1\\WebApplication1\\WS_stage_2017.asmx.cs:ligne 31

can anyone help me please ?

You need read permissions. Run as administrator visual stuio if debugging local. If running server you need set read permission your service application pool on iss.

Also this code wrong. Just one user can be execute. 2 clients can not open this file in the same time. You need use lock for this problem.

        [WebMethod]
    public List<string> getIdentifiants() {
        List<string> listA = new List<string>();
        List<string> listB = new List<string>();
        lock (this) {
            using (var fs = File.OpenRead(@"C:\Users\stag01\Desktop\identifiants.csv"))
            using (var reader = new StreamReader(fs)) {

                while (!reader.EndOfStream) {
                    var line = reader.ReadLine();
                    var values = line.Split(';');

                    listA.Add(values[0]);
                    listB.Add(values[1]);
                }
            } 
        } 
        return listA;

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM