当前位置: 首页>>代码示例>>C#>>正文


C# FileInfo.OpenText方法代码示例

本文整理汇总了C#中System.IO.FileInfo.OpenText方法的典型用法代码示例。如果您正苦于以下问题:C# FileInfo.OpenText方法的具体用法?C# FileInfo.OpenText怎么用?C# FileInfo.OpenText使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.IO.FileInfo的用法示例。


在下文中一共展示了FileInfo.OpenText方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: execute

        public void execute(string file_path)
        {
            // read script
            var file = new FileInfo(file_path);
            string script = file.OpenText().ReadToEnd();

            // execute script
            var connection = new SqlConnection(connection_string);
            var server = new Server(new ServerConnection(connection));
            server.ConnectionContext.ExecuteNonQuery(script);
            System.Diagnostics.Debug.WriteLine("Server Instance Name: " + server.InstanceName);
            file.OpenText().Close();
        }
开发者ID:soccerazy,项目名称:roy,代码行数:13,代码来源:sql_script.cs

示例2: ClearCreateCoreEntitiesDatabase

 public static void ClearCreateCoreEntitiesDatabase()
 {
     var clearFile = new FileInfo(ClearCoreEntitiesDatabaseScriptLocation);
     var createFile = new FileInfo(CreateCoreEntitiesDatabaseScriptLocation);
     string clearScript = clearFile.OpenText().ReadToEnd();
     string createScript = createFile.OpenText().ReadToEnd();
     using (var conn = new SqlConnection(ServerConstants.SqlConnectionString))
     {
         var server = new Microsoft.SqlServer.Management.Smo.Server(new ServerConnection(conn));
         server.ConnectionContext.ExecuteNonQuery(clearScript);
         server.ConnectionContext.ExecuteNonQuery(createScript);
     }
     clearFile.OpenText().Close();
     createFile.OpenText().Close();
 }
开发者ID:FoundOPS,项目名称:server,代码行数:15,代码来源:CoreEntitiesServerManagement.cs

示例3: Initialize

        public void Initialize()
        {
            ApiService.SubscribeOnce("api_start2", delegate
            {
                var rDataFile = new FileInfo(DataFilename);
                if (!rDataFile.Exists)
                    Infos = new Dictionary<int, QuestInfo>();
                else
                    using (var rReader = new JsonTextReader(rDataFile.OpenText()))
                    {
                        var rData = JArray.Load(rReader);

                        Infos = rData.Select(r => new QuestInfo(r)).ToDictionary(r => r.ID);
                    }

                if (r_InitializationLock != null)
                {
                    r_InitializationLock.Set();
                    r_InitializationLock.Dispose();
                    r_InitializationLock = null;
                }
            });

            ApiService.Subscribe("api_get_member/require_info", _ =>
            {
                if (r_InitializationLock != null)
                    r_InitializationLock.Wait();

                Progresses = RecordService.Instance.QuestProgress.Reload();
            });

            ApiService.Subscribe("api_get_member/questlist", r => ProcessQuestList(r.Data as RawQuestList));
            ApiService.Subscribe("api_req_quest/clearitemget", r => Progresses.Remove(int.Parse(r.Parameters["api_quest_id"])));
        }
开发者ID:amatukaze,项目名称:IntelligentNavalGun,代码行数:34,代码来源:QuestProgressService.cs

示例4: GetEntries

        public override IEnumerable<LogItem> GetEntries(string dataSource, FilterParams filter)
        {
            if (String.IsNullOrEmpty(dataSource))
                throw new ArgumentNullException("dataSource");
            if (filter == null)
                throw new ArgumentNullException("filter");

            string pattern = filter.Pattern;
            if (String.IsNullOrEmpty(pattern))
                throw new NotValidValueException("filter pattern null");

            FileInfo file = new FileInfo(dataSource);
            if (!file.Exists)
                throw new FileNotFoundException("file not found", dataSource);

            Regex regex = new Regex(@"%\b(date|message|level)\b");
            MatchCollection matches = regex.Matches(pattern);

            using (StreamReader reader = file.OpenText())
            {
                string s;
                while ((s = reader.ReadLine()) != null)
                {
                    string[] items = s.Split(new[] { Separator }, StringSplitOptions.RemoveEmptyEntries);
                    LogItem entry = CreateEntry(items, matches);
                    entry.Logger = filter.Logger;
                    yield return entry;
                }
            }            
        }
开发者ID:LukePet,项目名称:YALV,代码行数:30,代码来源:FileEntriesProvider.cs

示例5: runFileInfo

        static void runFileInfo()
        {
            string path = Path.GetTempFileName();
            FileInfo fi = new FileInfo(path);

            if (!fi.Exists)
            {
                // create a file to write to.
                using (StreamWriter writer = fi.CreateText())
                {
                    writer.WriteLine("Hello");
                    writer.WriteLine("And");
                    writer.WriteLine("Welcome");
                }
            }

            // open the file to read from.
            using (StreamReader reader = fi.OpenText())
            {
                string s = "";
                while ((s = reader.ReadLine()) != null)
                {
                    Console.WriteLine(s);
                }
            }
        }
开发者ID:sangwook236,项目名称:general-development-and-testing,代码行数:26,代码来源:IO.cs

示例6: Send_Click

        private void Send_Click(object sender, EventArgs e)
        {
            try
            {
                Output.Text = string.Empty;
                FileInfo file = new FileInfo(_file);
                StreamReader rdr = file.OpenText();
                string messageBody = rdr.ReadToEnd();
                rdr.Dispose();

                SmtpClient client = new SmtpClient("some.mail.server.example.com");
                client.Credentials = new NetworkCredential("someuser", "somepassword");
                MailAddress from = new MailAddress("[email protected]");
                MailAddress to = new MailAddress("[email protected]");
                MailMessage msg = new MailMessage(from, to);
                msg.Body = messageBody;
                msg.Subject = "Test message";
                //client.Send(msg);

                Output.Text = "Sent email with body: " + Environment.NewLine + messageBody;
            }
            catch (Exception ex)
            {
                Output.Text = ex.ToString();
            }
        }
开发者ID:jheintz,项目名称:presentations-and-training,代码行数:26,代码来源:Form1.cs

示例7: TestCollapseMessageResponses

      public void TestCollapseMessageResponses()
      {
         DirectoryInfo di = Directory.GetParent(Environment.CurrentDirectory);

         FileInfo fi = new FileInfo(Path.Combine(di.FullName, "TestSetup\\ExportCommandWithEMessages.xml"));
         TextReader reader = fi.OpenText();
         XDocument xdoc = XDocument.Load(reader);
         ////bool result = TestHelper.ValidateCommandXML(xdoc);
         ////Assert.IsTrue(result);
         IRoot root = new Root(TestConfig.RepositoryPath, TestConfig.ModuleName, TestConfig.CVSHost, TestConfig.CVSPort, TestConfig.Username, TestConfig.Password);
         root.WorkingDirectory = TestConfig.WorkingDirectory;
         PServerFactory factory = new PServerFactory();
         IConnection connection = new PServerConnection();
         ICommand cmd = factory.CreateCommand(xdoc, new object[] { root, connection });
         int count = cmd.Items.OfType<IResponse>().Count();
         Assert.AreEqual(18, count);
         count = cmd.Items.OfType<EMessageResponse>().Count();
         Assert.AreEqual(12, count);
         IList<IResponse> responses = cmd.Items.OfType<IResponse>().ToList();
         IList<IResponse> condensed = ResponseHelper.CollapseMessagesInResponses(responses);
         Assert.AreEqual(7, condensed.Count);
         IMessageResponse message = (IMessageResponse)condensed[5];
         Assert.AreEqual(12, message.Lines.Count);
         Console.WriteLine(message.Display());
      }
开发者ID:AnnieBougie,项目名称:CVS-Library-Net,代码行数:25,代码来源:ResponseHelperTest.cs

示例8: ExecuteTask

        protected override void ExecuteTask()
        {
            if (DebugTask && !System.Diagnostics.Debugger.IsAttached) System.Diagnostics.Debugger.Launch();

            NAnt.Contrib.Functions.FileFunctions contribFileFunctions = new Contrib.Functions.FileFunctions(base.Project, base.Properties);

            if (null != InElement && 0 < InElement.Count && 0 < InElement[0].FileNames.Count)
            {
                for (int idx = 0; idx < InElement.Count; idx++)
                {
                    FileSet fs = InElement[idx];
                    for (int idx2 = 0; idx2 < fs.FileNames.Count; idx2++)
                    {
                        FileInfo fileToCheck = new FileInfo(fs.FileNames[idx2]);
                        FileInfo checksumFile = new FileInfo(fileToCheck.FullName + '.' + Algorithm);

                        if (!checksumFile.Exists) throw new FileNotFoundException("Can't find checksum file", checksumFile.FullName);
                        if (!fileToCheck.Exists) throw new FileNotFoundException("Can't find file to check", fileToCheck.FullName);

                        string actualChecksum = contribFileFunctions.GetChecksum(fileToCheck.FullName, Algorithm);
                        using (StreamReader sr = checksumFile.OpenText())
                        {
                            string expectedChecksum = sr.ReadToEnd();
                            if (actualChecksum != expectedChecksum) throw new Exception(string.Format("The checksum generated does not match the contents of the file's counterpart.  Actual [{0}] from [{1}] was expected to be [{2}]", actualChecksum, fileToCheck.FullName, expectedChecksum));
                        }
                    }
                }
            }
        }
开发者ID:stunney,项目名称:NAntExtensions,代码行数:29,代码来源:ValidateChecksum.cs

示例9: GetConnectionString

        public static string GetConnectionString()
        {
            string str = "";

            Aes.KeySize keysize;

            keysize = Aes.KeySize.Bits128;
            byte[] cipherText = new byte[16];
            byte[] decipheredText = new byte[16];
            FileInfo inf = new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "settings.dat");
            if (inf.Exists)
            {
                StreamReader reader = inf.OpenText();
                gConnectionParam.setServer(reader.ReadLine());
                gConnectionParam.setUserName(reader.ReadLine());
                //base.Server = reader.ReadLine();
                //base.UserName = reader.ReadLine();

                cipherText = Encoding.Unicode.GetBytes(reader.ReadLine());
                AesLib.Aes a = new Aes(keysize, new byte[16]);
                a.InvCipher(cipherText, decipheredText);

                //Password = Encoding.Unicode.GetString(decipheredText);
                gConnectionParam.setPassword(Encoding.Unicode.GetString(decipheredText));

                //base.Database = reader.ReadLine();
                gConnectionParam.setDatabase(reader.ReadLine());
                // Fix error : error for There is already an open DataReader associated with this Command which must be closed first ("MultipleActiveResultSets=True;")
                str = gConnectionParam.getConnString();

            }
            return str;
        }
开发者ID:huutruongqnvn,项目名称:vnecoo01,代码行数:33,代码来源:FrmDBConfig.cs

示例10: XCProject

    public XCProject(string filePath) : this()
    {
        if (!System.IO.Directory.Exists(filePath))
        {
            Debug.LogWarning("Path does not exists.");
            return;
        }

        if (filePath.EndsWith(".xcodeproj"))
        {
            this.projectRootPath = Path.GetDirectoryName(filePath);
            this.filePath = filePath;
        }
        else
        {
            string[] projects = System.IO.Directory.GetDirectories(filePath, "*.xcodeproj");
            if (projects.Length == 0)
            {
                Debug.LogWarning("Error: missing xcodeproj file");
                return;
            }

            this.projectRootPath = filePath;
            this.filePath = projects[0];
        }

        projectFileInfo = new FileInfo(Path.Combine(this.filePath, "project.pbxproj"));
        StreamReader sr = projectFileInfo.OpenText();
        string contents = sr.ReadToEnd();
        sr.Close();

        PBXParser parser = new PBXParser();
        _datastore = parser.Decode(contents);
        if (_datastore == null)
        {
            throw new System.Exception("Project file not found at file path " + filePath);
        }

        if (!_datastore.ContainsKey("objects"))
        {
            Debug.Log("Errore " + _datastore.Count);
            return;
        }

        _objects = (PBXDictionary) _datastore["objects"];
        modified = false;

        _rootObjectKey = (string) _datastore["rootObject"];
        if (!string.IsNullOrEmpty(_rootObjectKey))
        {
            _project = new PBXProject(_rootObjectKey, (PBXDictionary) _objects[_rootObjectKey]);
            _rootGroup = new PBXGroup(_rootObjectKey, (PBXDictionary) _objects[_project.mainGroupID]);
        }
        else
        {
            Debug.LogWarning("Error: project has no root object");
            _project = null;
            _rootGroup = null;
        }
    }
开发者ID:jose-castillo,项目名称:SoundPuzzle,代码行数:60,代码来源:XCProject.cs

示例11: PowerShellProvider

 public PowerShellProvider(FileInfo scriptFile)
 {
     using(var reader = scriptFile.OpenText())
     {
         DestinationPath = reader.ReadToEnd();
     }
 }
开发者ID:thedersen,项目名称:ConDep,代码行数:7,代码来源:PowerShellProvider.cs

示例12: TemplateException

        /// <summary>
        /// Retrieves a template from the system, compiling it if needed.
        /// </summary>
        public ITemplate this[FileInfo file]
        {
            get
            {
                // Check the hash
                ITemplate template = (ITemplate) templates[file.FullName];

                if (template != null)
                    return template;

                // Ignore blanks
                if (!file.Exists)
                {
                    throw new TemplateException("File does not exist: "
                        + file);
                }

                // Create the template
                Debug("Parsing template: " + file);
                TextReader reader = file.OpenText();
                template = factory.Create(reader, file.ToString());
                reader.Close();

                // Save the template and return it
                templates[file.FullName] = template;
                return template;
            }
        }
开发者ID:DF-thangld,项目名称:web_game,代码行数:31,代码来源:TemplateManager.cs

示例13: Import

        public void Import(MigrationToolSettings settings)
        {
            var sourceImportFilePath = Path.Combine(settings.SourceDirectory, "localization-resource-translations.sql");
            if (!File.Exists(sourceImportFilePath))
            {
                throw new IOException($"Source file '{sourceImportFilePath}' for import not found!");
            }

            // create DB structures in target database
            using (var db = new LanguageEntities(settings.ConnectionString))
            {
                var resource = db.LocalizationResources.Where(r => r.Id == 0);
            }

            var fileInfo = new FileInfo(sourceImportFilePath);
            var script = fileInfo.OpenText().ReadToEnd();
            using (var connection = new SqlConnection(settings.ConnectionString))
            {
                connection.Open();

                using (var command = new SqlCommand(script, connection))
                {
                    command.ExecuteNonQuery();
                }
            }
        }
开发者ID:valdisiljuconoks,项目名称:LocalizationProvider,代码行数:26,代码来源:ResourceImporter.cs

示例14: Thesaurus

        /// <summary>
        /// Инициализирует новый экземпляр класса Thesaurus, сопоставляя его с текстовым файлом на диске.
        /// </summary>
        /// <param name="fileName">Имя файла.</param>
        public Thesaurus(string fileName)
        {
            List<int> indicies = new List<int>();
            indicies.Add(0); //первое слово начинается с нулевого символа

            fi = new FileInfo(fileName);
            var sr = fi.OpenText();
            _size = 0;
            int i = 0;
            while (/*!sr.EndOfStream*/true)
            {
                ++i;
                if (sr.Read() == '\n')
                {
                    indicies.Add(i); //запомнили новый индекс
                    ++_size;  //увеличили размер словаря
                }
                if (sr.EndOfStream)
                {
                    indicies.Add(i+2);
                    ++_size; //////test
                    break;
                }
            }
            sr.Close();
            _indicies = indicies.ToArray();
        }
开发者ID:Corpseintube0,项目名称:DataGenerate,代码行数:31,代码来源:Thesaurus.cs

示例15: CreateStoredFuncs

        public static void CreateStoredFuncs(string path)
        {
            var connectionString = ConfigurationManager.ConnectionStrings["ApplicationDbContext"].ConnectionString;

            var file = new FileInfo(path);
            var script = file.OpenText().ReadToEnd();

            using (var connection = new SqlConnection(connectionString))
            {
                var server = new Server(new ServerConnection(connection));
                server.ConnectionContext.ExecuteNonQuery(script);

                var _path = path.Replace("userdefinedtypes", "storedfunc");
                file = new FileInfo(_path);
                script = file.OpenText().ReadToEnd();
                server.ConnectionContext.ExecuteNonQuery(script);

                _path = _path.Replace("storedfunc", "storedproc");
                file = new FileInfo(_path);
                script = file.OpenText().ReadToEnd();
                server.ConnectionContext.ExecuteNonQuery(script);

                _path = _path.Replace("storedproc", "storedtriggers");
                file = new FileInfo(_path);
                script = file.OpenText().ReadToEnd();
                server.ConnectionContext.ExecuteNonQuery(script);
            }
        }
开发者ID:densem-2013,项目名称:ACSDining,代码行数:28,代码来源:Utility.cs


注:本文中的System.IO.FileInfo.OpenText方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。