OpenText() public static méthode

public static OpenText ( String path ) : StreamReader
path String
Résultat StreamReader
    /// <summary>
    ///     Opens a <see cref="StreamReader" /> to read text from a file.
    /// </summary>
    /// <param name="path">The path of the file.</param>
    /// <returns>
    ///     A <see cref="StreamReader" /> that can read from a file.
    /// </returns>
    /// <exception cref="ArgumentNullException">
    ///     <paramref name="path" /> is <see langword="null" /> (<see langword="Nothing" /> in Visual Basic).
    /// </exception>
    public StreamReader OpenText(string path)
    {
        _ = Requires.NotNullOrWhiteSpace(
            path,
            nameof(path));

        return(FSFile.OpenText(path));
    }
Exemple #2
0
    public InstallationSummary InstallCompiledPackageData(
        FileInfo packageXmlFile,
        int userId = Constants.Security.SuperUserId)
    {
        XDocument xml;

        using (StreamReader streamReader = File.OpenText(packageXmlFile.FullName))
        {
            xml = XDocument.Load(streamReader);
        }

        return(InstallCompiledPackageData(xml, userId));
    }
Exemple #3
0
        public string ReadProtectedFile(string role)
        {
            var textFile = FileBuilder
                           .Create(FileTypes.Text)
                           .WithAuthorization()
                           .Build();

            if (textFile == null)
            {
                throw new FileNotFoundException();
            }

            if (!_fileSecurity.CanAccessFile(role))
            {
                return($"ACCESS DENIED: The role \"{role}\" is not authorized to access this file.");
            }

            using (var file = File.OpenText(textFile.FilePath))
            {
                return(file.ReadToEnd());
            }
        }
Exemple #4
0
        static void Main(string[] args)
        {
            var cmdArguments = Parser.Default.ParseArguments <CommandLineOptions>(args);

            var exitCode = cmdArguments
                           .MapResult(
                options =>
            {
                var settings = new CloudSettings
                {
                    Protocol = options.Protocol
                };

                var repoFabric = new RepoFabric(settings, new Credentials(string.Empty, string.Empty));
                var repo       = repoFabric.Create();

                var cards = new List <string>();
                cards.AddRange(options.Files);

                foreach (string filelist in options.Filelists)
                {
                    if (!string.IsNullOrEmpty(filelist))
                    {
                        if (!File.Exists(filelist))
                        {
                            throw new FileNotFoundException($"List file not found {filelist}");
                        }
                        using (TextReader reader = File.OpenText(filelist))
                        {
                            string line;
                            while (!string.IsNullOrEmpty(line = reader.ReadLine()))
                            {
                                cards.Add(line);
                            }
                        }
                    }
                }

                foreach (var card in cards)
                {
                    string pattern = Path.GetFileName(card);
                    string path    = card.Substring(0, card.Length - pattern.Length);
                    string absPath = Path.GetFullPath(string.IsNullOrEmpty(path) ? "." : path);

                    // "Illegal characters in path" exception for wildcard on .Net48
                    //string absPathWithFilename = Path.GetFullPath(card);
                    //string absPath = Path.GetDirectoryName(string.IsNullOrEmpty(path) ? "." : path);

                    string[] filenames = Directory.GetFiles(absPath, pattern,
                                                            options.IsRecursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);

                    foreach (var filename in filenames)
                    {
                        var hasher = repo.GetHasher();
                        long size;
                        using (FileStream fs = File.OpenRead(filename))
                        {
                            hasher.Append(fs);
                            size = fs.Length;
                        }

                        string hashString = hasher.Hash.ToString();
                        Console.WriteLine($"{hashString}\t{hasher.Name}\t{size}\t{filename}");

                        //Console.WriteLine($"{filename}" );
                    }
                }

                return(0);
            },
                errors => 1);

            if (exitCode > 0)
            {
                Environment.Exit(exitCode);
            }
        }
Exemple #5
0
        public static void ConvertJSON(string path)
        {
            if (File.Exists(path))
            {
                try
                {
                    int    totalLines = File.ReadLines(path).Count();
                    string jsonPath   = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Employees.json");
                    using (StreamReader fileReader = File.OpenText(path))
                    {
                        string   title = Path.GetFileNameWithoutExtension(path).ToLower();
                        string   line;
                        string[] titles  = new string[] { };
                        int      counter = 0;

                        //using (StreamWriter fileWriter = File.CreateText(jsonPath))
                        using (StreamWriter fileWriter = File.CreateText(jsonPath + "/" + title + ".json"))
                        {
                            //apriamo le parentesi
                            fileWriter.WriteLine("{");
                            fileWriter.WriteLine("\"" + title + "\":[");

                            while ((line = fileReader.ReadLine()) != null)
                            {
                                if (counter == 0)
                                {
                                    line   = line.ToLower();
                                    titles = line.Split(",");
                                    counter++;
                                }

                                else
                                {
                                    string[] data = new string[] { };
                                    data = line.Split(",");

                                    fileWriter.Write("{");
                                    for (int i = 0; i < titles.Length; i++)
                                    {
                                        if (i == title.Length - 1) // se è l'ultimo
                                        {
                                            fileWriter.Write("\"" + titles[i] + "\":\"" + data[i] + "\"");
                                        }
                                        else
                                        {
                                            fileWriter.Write("\"" + titles[i] + "\":\"" + data[i] + "\",");
                                        }
                                    }

                                    if (counter != totalLines - 1) // se non è l'ultima riga
                                    {
                                        fileWriter.Write("},\n");
                                    }
                                    else
                                    {
                                        fileWriter.Write("}\n");
                                    }
                                }
                            }

                            fileWriter.WriteLine("]}");
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
        }
Exemple #6
0
        public async static Task LetturaScritturaFileAsync2()
        {
            //piu step:
            //creo cartella + sottocarte con file


            DirectoryInfo directory = new DirectoryInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), "ProvaLetturascrittura"));

            try
            {
                //creazione cartelle
                directory.Create();
                Console.WriteLine(" cartella creata");
                directory.CreateSubdirectory("ProvaScrittura");
                Console.WriteLine("Subdirectory creata correttamente");

                //creazionefile
                string path = Path.Combine(directory.FullName, "ProvaScrittura/SequenzaNumeri.txt"); //parti da directory
                using (StreamWriter file = File.CreateText(path))                                    //uso stramwriter per scrivere nel file
                {
                    for (int i = 0; i <= 10; i++)
                    {
                        await file.WriteAsync(i.ToString() + "\n");// conversione in stringa
                    }
                }
                using (StreamWriter file = File.AppendText(path))// se avessi lascito create avrebbe sovrascritto, in questo modo aggiungo
                {
                    for (int i = 10; i <= 20; i++)
                    {
                        await file.WriteAsync(i.ToString() + "\n");// conversione in stringa
                    }
                }

                // letturafile
                string line;
                int    counter = 0; //mi dice a che riga sono

                using (StreamReader fileReader = File.OpenText(path))
                {
                    while ((line = fileReader.ReadLine()) != null) // mostro a schermo la riga
                    {
                        Console.WriteLine(line);
                        counter++;
                    }
                    line = ""; //resetto la riga
                    fileReader.BaseStream.Position = 0;

                    //lettura totale del test
                    line = fileReader.ReadToEnd();
                    Console.WriteLine(line);  // mi mette tutto in una riga


                    //split
                    string[] linesplit = line.Split("\n"); //divide in base ad una separatore

                    foreach (string el in linesplit)
                    {
                        Console.Write(el + " ");
                    }
                }
            }
            catch (Exception e)
            { Console.WriteLine(e.Message); }
        }
        private static void ImportCCL(string cclVersion)
        {
            var    eaRepository     = new Repository();
            string originalRepoPath = Directory.GetCurrentDirectory() + string.Format(@"\..\..\resources\{0}\Repository-with-CDTs.eap", cclVersion);
            string targetRepoPath   = originalRepoPath.WithoutSuffix(".eap") + "-and-CCs.eap";

            File.Copy(originalRepoPath, targetRepoPath, true);
            eaRepository.OpenFile(targetRepoPath);
            ICctsRepository cctsRepository = CctsRepositoryFactory.CreateCctsRepository(eaRepository);
            var             bLibrary       = cctsRepository.GetBLibraryByPath((Path)"Model" / "bLibrary");
            var             cdtLibrary     = bLibrary.GetCdtLibraryByName("CDTLibrary");

            var cdts = new Dictionary <string, ICdt>();

            foreach (ICdt cdt in cdtLibrary.Cdts)
            {
                cdts[cdt.Name] = cdt;
            }

            ICcLibrary ccLibrary = bLibrary.CreateCcLibrary(new CcLibrarySpec
            {
                Name = "CCLibrary",
                VersionIdentifier = cclVersion
            });

            StreamReader reader = File.OpenText(string.Format(@"..\..\resources\{0}\{0}-CCs.txt", cclVersion));
            String       line;
            var          accSpecs  = new List <AccSpec>();
            var          asccSpecs = new Dictionary <string, List <AsccSpecWithAssociatedAccName> >();
            AccSpec      accSpec   = null;

            while ((line = reader.ReadLine()) != null)
            {
                LineNumber++;
                if (LineNumber < 2)
                {
                    continue;
                }

                if (Debug)
                {
                    if (LineNumber > 150)
                    {
                        break;
                    }
                }

                Record record = GetRecord(line);

                switch (record.ElementType)
                {
                case "ACC":
                    CheckACCRecord(record);
                    accSpec = new AccSpec
                    {
                        UniqueIdentifier  = record.UniqueUNAssignedID,
                        Name              = GetACCName(record),
                        Definition        = record.Definition.LimitTo(MaximumTaggedValueLength),
                        BusinessTerms     = ToArray(record.BusinessTerms.LimitTo(MaximumTaggedValueLength)),
                        UsageRules        = ToArray(record.UsageRules.LimitTo(MaximumTaggedValueLength)),
                        VersionIdentifier = record.Version,
                        Bccs              = new List <BccSpec>(),
                        Asccs             = new List <AsccSpec>(),
                    };
                    accSpecs.Add(accSpec);
                    break;

                case "BCC":
                    if (accSpec == null)
                    {
                        throw new Exception("The first record must specify an ACC.");
                    }
                    CheckBCCRecord(record, accSpec.Name);
                    var bccSpec = new BccSpec
                    {
                        UniqueIdentifier    = record.UniqueUNAssignedID,
                        Definition          = record.Definition.LimitTo(MaximumTaggedValueLength),
                        DictionaryEntryName = record.DictionaryEntryName,
                        Name              = QualifiedName(record.PropertyTermQualifiers, record.PropertyTerm),
                        BusinessTerms     = ToArray(record.BusinessTerms.LimitTo(MaximumTaggedValueLength)),
                        UsageRules        = ToArray(record.UsageRules.LimitTo(MaximumTaggedValueLength)),
                        SequencingKey     = record.SequenceNumber,
                        LowerBound        = MapOccurrence(record.OccurrenceMin),
                        UpperBound        = MapOccurrence(record.OccurrenceMax),
                        VersionIdentifier = record.Version,
                        Cdt = FindCDT(record.RepresentationTerm.AsName(), cdts)
                    };
                    if (bccSpec.Cdt == null)
                    {
                        Console.WriteLine("WARNING: Skipping line {0}: CDT not found: <{1}>.", LineNumber, record.RepresentationTerm);
                        continue;
                    }
                    accSpec.Bccs.Add(bccSpec);
                    break;

                case "ASCC":
                    if (accSpec == null)
                    {
                        throw new Exception("The first record must specify an ACC.");
                    }
                    CheckASCCRecord(record, accSpec.Name);
                    var asccSpec = new AsccSpecWithAssociatedAccName
                    {
                        UniqueIdentifier  = record.UniqueUNAssignedID,
                        Definition        = record.Definition.LimitTo(MaximumTaggedValueLength),
                        Name              = QualifiedName(record.PropertyTermQualifiers, record.PropertyTerm),
                        BusinessTerms     = ToArray(record.BusinessTerms.LimitTo(MaximumTaggedValueLength)),
                        UsageRules        = ToArray(record.UsageRules.LimitTo(MaximumTaggedValueLength)),
                        SequencingKey     = record.SequenceNumber,
                        LowerBound        = MapOccurrence(record.OccurrenceMin),
                        UpperBound        = MapOccurrence(record.OccurrenceMax),
                        VersionIdentifier = record.Version,
                        AssociatedAccName = record.AssociatedObjectClass.AsName(),
                    };
                    asccSpecs.GetAndCreate(accSpec.Name).Add(asccSpec);
                    break;

                default:
                    Console.WriteLine("WARNING: Skipping line {0}.", LineNumber);
                    break;
                }
            }
            reader.Close();

            try
            {
                ACCImporter.ImportACCs(ccLibrary, accSpecs, asccSpecs);
            }
            finally
            {
                eaRepository.CloseFile();
            }
            Console.WriteLine("INFO: Number of ACCs: " + accSpecs.Count);
            Console.WriteLine("Press a key to continue...");
            Console.ReadKey();
        }
Exemple #8
0
    private void ThreadGetClientMD5(object _value)
    {
        //先从服务器拉下整个客户端的md5list
        //临时文件路径,获取md5列表
        try
        {
            var tempPath = m_MainForm.m_downloadPath + "/" + m_MainForm.m_clientmd5Txt;
            _ServerUpdateStructs = new Dictionary <string, MyUpdateStruct>();
            StreamReader sR = File.OpenText(tempPath);

            string nextLine;
            while ((nextLine = sR.ReadLine()) != null)
            {
                var strings        = nextLine.Split('=');
                var key            = strings[0];
                var value          = strings[1];
                var myUpdateStruct = new MyUpdateStruct();
                myUpdateStruct.PathKey = key;
                myUpdateStruct.Md5     = value;
                //启动器之前校验过,此处不作校验。
                _ServerUpdateStructs.Add(key, myUpdateStruct);
            }
            sR.Close();

            //本地MD5
            if (FileMatchUp.MakeEncodingList(_ServerUpdateStructs, m_MainForm.m_curDirectory, m_MainForm.m_clientmd5Txt) == true)
            {
                _ClientUpdateStructs.Clear();
                var          cilentFloder = m_MainForm.m_curDirectory + "/" + m_MainForm.m_clientmd5Txt;
                StreamReader sRclient     = File.OpenText(cilentFloder);
                string       nextLineclient;
                while ((nextLineclient = sRclient.ReadLine()) != null)
                {
                    var strings        = nextLineclient.Split('=');
                    var key            = strings[0];
                    var value          = strings[1];
                    var myUpdateStruct = new MyUpdateStruct();
                    myUpdateStruct.PathKey = key;
                    myUpdateStruct.Md5     = value;
                    _ClientUpdateStructs.Add(key, myUpdateStruct);
                }
                sRclient.Close();

                //md5列表创建完成 比对需要下载的MD文件
                _DownLoadList.Clear();
                foreach (var serverUpdateStruct in _ServerUpdateStructs)
                {
                    var key       = serverUpdateStruct.Key;
                    var serverMd5 = serverUpdateStruct.Value.Md5;
                    if (_ClientUpdateStructs.ContainsKey(key))
                    {
                        var clientmd5 = _ClientUpdateStructs[key].Md5;
                        if (serverMd5 != clientmd5)
                        {
                            var myUpdateStruct = new MyUpdateStruct();
                            myUpdateStruct.PathKey = key;
                            myUpdateStruct.Md5     = serverMd5;
                            _DownLoadList.Add(myUpdateStruct.PathKey, myUpdateStruct);
                        }
                    }
                    else
                    {
                        var myUpdateStruct = new MyUpdateStruct();
                        myUpdateStruct.PathKey = key;
                        myUpdateStruct.Md5     = serverMd5;
                        _DownLoadList.Add(myUpdateStruct.PathKey, myUpdateStruct);
                    }
                }

                //下载列表中不一致的文件
                Step.CURRENT_STEP = Step.State.__StartNeedDownLoadFile;
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("文件对比失败:" + ex.Message);
        }
    }