Here are the examples of the csharp api System.IO.File.OpenText(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
666 Examples
19
Source : AscReader.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
public static async Task<AscData> ReadFileToAscData(
string filename, Func<float, Color> colorMapFunction, Action<int> reportProgress = null)
{
var result = await Task.Run(() =>
{
using (var file = File.OpenText(filename))
{
return ReadFromStream(file, colorMapFunction, reportProgress);
}
});
return result;
}
19
Source : AscReader.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
public static async Task<AscData> ReadFileToAscData(
string filename, Func<float, Color> colorMapFunction, Action<int> reportProgress = null)
{
AscData result = new AscData()
{
XValues = new List<float>(),
YValues = new List<float>(),
ZValues = new List<float>(),
ColorValues = new List<Color>(),
};
await Task.Run(() =>
{
using (var file = File.OpenText(filename))
{
// Load the ASC file format
result.NumberColumns = ReadInt(file, "ncols");
result.NumberRows = ReadInt(file, "nrows");
result.XllCorner = ReadInt(file, "xllcorner");
result.YllCorner = ReadInt(file, "yllcorner");
result.CellSize = ReadInt(file, "cellsize");
result.NoDataValue = ReadInt(file, "NODATA_value");
// Generate X-values based off cell position
float[] xValuesRow = Enumerable.Range(0, result.NumberColumns).Select(x => (float)x * result.CellSize).ToArray();
for (int i = 0; i < result.NumberRows; i++)
{
// Read heights from the ASC file and generate Z-cell values
float[] heightValuesRow = ReadFloats(file, " ", result.NoDataValue);
float[] zValuesRow = Enumerable.Repeat(0 + i * result.CellSize, result.NumberRows).Select(x => (float)x).ToArray();
result.XValues.AddRange(xValuesRow);
result.YValues.AddRange(heightValuesRow);
result.ZValues.AddRange(zValuesRow);
if (colorMapFunction != null)
{
// Optional color-mapping of points based on height
Color[] colorValuesRow = heightValuesRow
.Select(colorMapFunction)
.ToArray();
result.ColorValues.AddRange(colorValuesRow);
}
// Optional report loading progress 0-100%
reportProgress?.Invoke((int)(100.0f * i / result.NumberRows));
}
}
});
return result;
}
19
Source : Program_Setup.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
private static void DoOutOfBoxSetup(string configFile)
{
var exeLocation = Path.GetDirectoryName(System.Reflection.replacedembly.GetExecutingreplacedembly().Location);
var configJsExample = Path.Combine(exeLocation, "Config.js.example");
var exampleFile = new FileInfo(configJsExample);
if (!exampleFile.Exists)
{
log.Error("config.js.example Configuration file is missing. Please copy the file config.js.example to config.js and edit it to match your needs before running ACE.");
throw new Exception("missing config.js configuration file");
}
else
{
if (!IsRunningInContainer)
{
Console.WriteLine("config.js Configuration file is missing, cloning from example file.");
File.Copy(configJsExample, configFile, true);
}
else
{
Console.WriteLine("config.js Configuration file is missing, ACEmulator is running in a container, cloning from docker file.");
var configJsDocker = Path.Combine(exeLocation, "Config.js.docker");
File.Copy(configJsDocker, configFile, true);
}
}
var fileText = File.ReadAllText(configFile);
var config = JsonConvert.DeserializeObject<MasterConfiguration>(new JsMinifier().Minify(fileText));
Console.WriteLine("Performing setup for ACEmulator...");
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("Welcome to ACEmulator! To configure your world for first use, please follow the instructions below. Press enter at each prompt to accept default values.");
Console.WriteLine();
Console.WriteLine();
Console.Write($"Enter the name for your World (default: \"{config.Server.WorldName}\"): ");
var variable = Console.ReadLine();
if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_WORLD_NAME");
if (!string.IsNullOrWhiteSpace(variable))
config.Server.WorldName = variable.Trim();
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("The next two entries should use defaults, unless you have specific network environments...");
Console.WriteLine();
Console.WriteLine();
Console.Write($"Enter the Host address for your World (default: \"{config.Server.Network.Host}\"): ");
variable = Console.ReadLine();
if (!string.IsNullOrWhiteSpace(variable))
config.Server.Network.Host = variable.Trim();
Console.WriteLine();
Console.Write($"Enter the Port for your World (default: \"{config.Server.Network.Port}\"): ");
variable = Console.ReadLine();
if (!string.IsNullOrWhiteSpace(variable))
config.Server.Network.Port = Convert.ToUInt32(variable.Trim());
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
Console.Write($"Enter the directory location for your DAT files (default: \"{config.Server.DatFilesDirectory}\"): ");
variable = Console.ReadLine();
if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_DAT_FILES_DIRECTORY");
if (!string.IsNullOrWhiteSpace(variable))
{
var path = Path.GetFullPath(variable.Trim());
if (!Path.EndsInDirectorySeparator(path))
path += Path.DirectorySeparatorChar;
//path = path.Replace($"{Path.DirectorySeparatorChar}", $"{Path.DirectorySeparatorChar}{Path.DirectorySeparatorChar}");
config.Server.DatFilesDirectory = path;
}
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("Next we will configure your SQL server connections. You will need to know your database name, username and preplacedword for each.");
Console.WriteLine("Default names for the databases are recommended, and it is also recommended you not use root for login to database. The preplacedword must not be blank.");
Console.WriteLine("It is also recommended the SQL server be hosted on the same machine as this server, so defaults for Host and Port would be ideal as well.");
Console.WriteLine("As before, pressing enter will use default value.");
Console.WriteLine();
Console.WriteLine();
Console.Write($"Enter the database name for your authentication database (default: \"{config.MySql.Authentication.Database}\"): ");
variable = Console.ReadLine();
if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_AUTH_DATABASE_NAME");
if (!string.IsNullOrWhiteSpace(variable))
config.MySql.Authentication.Database = variable.Trim();
Console.WriteLine();
Console.Write($"Enter the database name for your shard database (default: \"{config.MySql.Shard.Database}\"): ");
variable = Console.ReadLine();
if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_SHARD_DATABASE_NAME");
if (!string.IsNullOrWhiteSpace(variable))
config.MySql.Shard.Database = variable.Trim();
Console.WriteLine();
Console.Write($"Enter the database name for your world database (default: \"{config.MySql.World.Database}\"): ");
variable = Console.ReadLine();
if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_WORLD_DATABASE_NAME");
if (!string.IsNullOrWhiteSpace(variable))
config.MySql.World.Database = variable.Trim();
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
Console.Write("Typically, all three databases will be on the same SQL server, is this how you want to proceed? (Y/n) ");
variable = Console.ReadLine();
if (IsRunningInContainer) variable = "n";
if (!variable.Equals("n", StringComparison.OrdinalIgnoreCase) && !variable.Equals("no", StringComparison.OrdinalIgnoreCase))
{
Console.Write($"Enter the Host address for your SQL server (default: \"{config.MySql.World.Host}\"): ");
variable = Console.ReadLine();
if (!string.IsNullOrWhiteSpace(variable))
{
config.MySql.Authentication.Host = variable.Trim();
config.MySql.Shard.Host = variable.Trim();
config.MySql.World.Host = variable.Trim();
}
Console.WriteLine();
Console.Write($"Enter the Port for your SQL server (default: \"{config.MySql.World.Port}\"): ");
variable = Console.ReadLine();
if (!string.IsNullOrWhiteSpace(variable))
{
config.MySql.Authentication.Port = Convert.ToUInt32(variable.Trim());
config.MySql.Shard.Port = Convert.ToUInt32(variable.Trim());
config.MySql.World.Port = Convert.ToUInt32(variable.Trim());
}
Console.WriteLine();
}
else
{
Console.Write($"Enter the Host address for your authentication database (default: \"{config.MySql.Authentication.Host}\"): ");
variable = Console.ReadLine();
if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_AUTH_DATABASE_HOST");
if (!string.IsNullOrWhiteSpace(variable))
config.MySql.Authentication.Host = variable.Trim();
Console.WriteLine();
Console.Write($"Enter the Port for your authentication database (default: \"{config.MySql.Authentication.Port}\"): ");
variable = Console.ReadLine();
if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_AUTH_DATABASE_PORT");
if (!string.IsNullOrWhiteSpace(variable))
config.MySql.Authentication.Port = Convert.ToUInt32(variable.Trim());
Console.WriteLine();
Console.Write($"Enter the Host address for your shard database (default: \"{config.MySql.Shard.Host}\"): ");
variable = Console.ReadLine();
if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_SHARD_DATABASE_HOST");
if (!string.IsNullOrWhiteSpace(variable))
config.MySql.Shard.Host = variable.Trim();
Console.WriteLine();
Console.Write($"Enter the Port for your shard database (default: \"{config.MySql.Shard.Port}\"): ");
variable = Console.ReadLine();
if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_SHARD_DATABASE_PORT");
if (!string.IsNullOrWhiteSpace(variable))
config.MySql.Shard.Port = Convert.ToUInt32(variable.Trim());
Console.WriteLine();
Console.Write($"Enter the Host address for your world database (default: \"{config.MySql.World.Host}\"): ");
variable = Console.ReadLine();
if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_WORLD_DATABASE_HOST");
if (!string.IsNullOrWhiteSpace(variable))
config.MySql.World.Host = variable.Trim();
Console.WriteLine();
Console.Write($"Enter the Port for your world database (default: \"{config.MySql.World.Port}\"): ");
variable = Console.ReadLine();
if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_WORLD_DATABASE_PORT");
if (!string.IsNullOrWhiteSpace(variable))
config.MySql.World.Port = Convert.ToUInt32(variable.Trim());
Console.WriteLine();
}
Console.WriteLine();
Console.WriteLine();
Console.Write("Typically, all three databases will be on the using the same SQL server credentials, is this how you want to proceed? (Y/n) ");
variable = Console.ReadLine();
if (IsRunningInContainer) variable = "y";
if (!variable.Equals("n", StringComparison.OrdinalIgnoreCase) && !variable.Equals("no", StringComparison.OrdinalIgnoreCase))
{
Console.Write($"Enter the username for your SQL server (default: \"{config.MySql.World.Username}\"): ");
variable = Console.ReadLine();
if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("MYSQL_USER");
if (!string.IsNullOrWhiteSpace(variable))
{
config.MySql.Authentication.Username = variable.Trim();
config.MySql.Shard.Username = variable.Trim();
config.MySql.World.Username = variable.Trim();
}
Console.WriteLine();
Console.Write($"Enter the preplacedword for your SQL server (default: \"{config.MySql.World.Preplacedword}\"): ");
variable = Console.ReadLine();
if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("MYSQL_PreplacedWORD");
if (!string.IsNullOrWhiteSpace(variable))
{
config.MySql.Authentication.Preplacedword = variable.Trim();
config.MySql.Shard.Preplacedword = variable.Trim();
config.MySql.World.Preplacedword = variable.Trim();
}
}
else
{
Console.Write($"Enter the username for your authentication database (default: \"{config.MySql.Authentication.Username}\"): ");
variable = Console.ReadLine();
if (!string.IsNullOrWhiteSpace(variable))
config.MySql.Authentication.Username = variable.Trim();
Console.WriteLine();
Console.Write($"Enter the preplacedword for your authentication database (default: \"{config.MySql.Authentication.Preplacedword}\"): ");
variable = Console.ReadLine();
if (!string.IsNullOrWhiteSpace(variable))
config.MySql.Authentication.Preplacedword = variable.Trim();
Console.WriteLine();
Console.Write($"Enter the username for your shard database (default: \"{config.MySql.Shard.Username}\"): ");
variable = Console.ReadLine();
if (!string.IsNullOrWhiteSpace(variable))
config.MySql.Shard.Username = variable.Trim();
Console.WriteLine();
Console.Write($"Enter the preplacedword for your shard database (default: \"{config.MySql.Shard.Preplacedword}\"): ");
variable = Console.ReadLine();
if (!string.IsNullOrWhiteSpace(variable))
config.MySql.Shard.Preplacedword = variable.Trim();
Console.WriteLine();
Console.Write($"Enter the username for your world database (default: \"{config.MySql.World.Username}\"): ");
variable = Console.ReadLine();
if (!string.IsNullOrWhiteSpace(variable))
config.MySql.World.Username = variable.Trim();
Console.WriteLine();
Console.Write($"Enter the preplacedword for your world database (default: \"{config.MySql.World.Preplacedword}\"): ");
variable = Console.ReadLine();
if (!string.IsNullOrWhiteSpace(variable))
config.MySql.World.Preplacedword = variable.Trim();
}
Console.WriteLine("commiting configuration to memory...");
using (StreamWriter file = File.CreateText(configFile))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Formatting = Formatting.Indented;
//serializer.NullValueHandling = NullValueHandling.Ignore;
//serializer.DefaultValueHandling = DefaultValueHandling.Ignore;
serializer.Serialize(file, config);
}
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
Console.Write("Do you want to ACEmulator to attempt to initilize your SQL databases? This will erase any existing ACEmulator specific databases that may already exist on the server (Y/n): ");
variable = Console.ReadLine();
if (IsRunningInContainer) variable = Convert.ToBoolean(Environment.GetEnvironmentVariable("ACE_SQL_INITIALIZE_DATABASES")) ? "y" : "n";
if (!variable.Equals("n", StringComparison.OrdinalIgnoreCase) && !variable.Equals("no", StringComparison.OrdinalIgnoreCase))
{
Console.WriteLine();
Console.Write($"Waiting for connection to SQL server at {config.MySql.World.Host}:{config.MySql.World.Port} .... ");
for (; ; )
{
try
{
using (var sqlTestConnection = new MySql.Data.MySqlClient.MySqlConnection($"server={config.MySql.World.Host};port={config.MySql.World.Port};user={config.MySql.World.Username};preplacedword={config.MySql.World.Preplacedword};DefaultCommandTimeout=120"))
{
Console.Write(".");
sqlTestConnection.Open();
}
break;
}
catch (MySql.Data.MySqlClient.MySqlException)
{
Console.Write(".");
Thread.Sleep(5000);
}
}
Console.WriteLine(" connected!");
if (IsRunningInContainer)
{
Console.Write("Clearing out temporary ace% database .... ");
var sqlDBFile = "DROP DATABASE `ace%`;";
var sqlConnectInfo = $"server={config.MySql.World.Host};port={config.MySql.World.Port};user={config.MySql.World.Username};preplacedword={config.MySql.World.Preplacedword};DefaultCommandTimeout=120";
var sqlConnect = new MySql.Data.MySqlClient.MySqlConnection(sqlConnectInfo);
var script = new MySql.Data.MySqlClient.MySqlScript(sqlConnect, sqlDBFile);
Console.Write($"Importing into SQL server at {config.MySql.World.Host}:{config.MySql.World.Port} .... ");
try
{
script.StatementExecuted += new MySql.Data.MySqlClient.MySqlStatementExecutedEventHandler(OnStatementExecutedOutputDot);
var count = script.Execute();
}
catch (MySql.Data.MySqlClient.MySqlException)
{
}
Console.WriteLine(" done!");
}
Console.WriteLine("Searching for base SQL scripts .... ");
foreach (var file in new DirectoryInfo($"DatabaseSetupScripts{Path.DirectorySeparatorChar}Base").GetFiles("*.sql").OrderBy(f => f.Name))
{
Console.Write($"Found {file.Name} .... ");
var sqlDBFile = File.ReadAllText(file.FullName);
var sqlConnectInfo = $"server={config.MySql.World.Host};port={config.MySql.World.Port};user={config.MySql.World.Username};preplacedword={config.MySql.World.Preplacedword};DefaultCommandTimeout=120";
switch (file.Name)
{
case "AuthenticationBase":
sqlConnectInfo = $"server={config.MySql.Authentication.Host};port={config.MySql.Authentication.Port};user={config.MySql.Authentication.Username};preplacedword={config.MySql.Authentication.Preplacedword};DefaultCommandTimeout=120";
break;
case "ShardBase":
sqlConnectInfo = $"server={config.MySql.Shard.Host};port={config.MySql.Shard.Port};user={config.MySql.Shard.Username};preplacedword={config.MySql.Shard.Preplacedword};DefaultCommandTimeout=120";
break;
}
var sqlConnect = new MySql.Data.MySqlClient.MySqlConnection(sqlConnectInfo);
var script = new MySql.Data.MySqlClient.MySqlScript(sqlConnect, sqlDBFile);
Console.Write($"Importing into SQL server at {config.MySql.World.Host}:{config.MySql.World.Port} .... ");
try
{
script.StatementExecuted += new MySql.Data.MySqlClient.MySqlStatementExecutedEventHandler(OnStatementExecutedOutputDot);
var count = script.Execute();
}
catch (MySql.Data.MySqlClient.MySqlException)
{
}
Console.WriteLine(" complete!");
}
Console.WriteLine("Base SQL scripts import complete!");
Console.WriteLine("Searching for Update SQL scripts .... ");
PatchDatabase("Authentication", config.MySql.Authentication.Host, config.MySql.Authentication.Port, config.MySql.Authentication.Username, config.MySql.Authentication.Preplacedword, config.MySql.Authentication.Database);
PatchDatabase("Shard", config.MySql.Shard.Host, config.MySql.Shard.Port, config.MySql.Shard.Username, config.MySql.Shard.Preplacedword, config.MySql.Shard.Database);
PatchDatabase("World", config.MySql.World.Host, config.MySql.World.Port, config.MySql.World.Username, config.MySql.World.Preplacedword, config.MySql.World.Database);
}
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
Console.Write("Do you want to download the latest world database and import it? (Y/n): ");
variable = Console.ReadLine();
if (IsRunningInContainer) variable = Convert.ToBoolean(Environment.GetEnvironmentVariable("ACE_SQL_DOWNLOAD_LATEST_WORLD_RELEASE")) ? "y" : "n";
if (!variable.Equals("n", StringComparison.OrdinalIgnoreCase) && !variable.Equals("no", StringComparison.OrdinalIgnoreCase))
{
Console.WriteLine();
if (IsRunningInContainer)
{
Console.WriteLine(" ");
Console.WriteLine("This process will take a while, depending on many factors, and may look stuck while reading and importing the world database, please be patient! ");
Console.WriteLine(" ");
}
Console.Write("Looking up latest release from ACEmulator/ACE-World-16PY-Patches .... ");
// webrequest code provided by OptimShi
var url = "https://api.github.com/repos/ACEmulator/ACE-World-16PY-Patches/releases";
var request = (HttpWebRequest)WebRequest.Create(url);
request.UserAgent = "Mozilla//5.0 (Windows NT 10.0; Win64; x64; rv:72.0) Gecko//20100101 Firefox//72.0";
request.UserAgent = "ACE.Server";
var response = request.GetResponse();
var reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8);
var html = reader.ReadToEnd();
reader.Close();
response.Close();
dynamic json = JsonConvert.DeserializeObject(html);
string tag = json[0].tag_name;
string dbURL = json[0].replacedets[0].browser_download_url;
string dbFileName = json[0].replacedets[0].name;
// webrequest code provided by OptimShi
Console.WriteLine($"Found {tag} !");
Console.Write($"Downloading {dbFileName} .... ");
using (var client = new WebClient())
{
client.DownloadFile(dbURL, dbFileName);
}
Console.WriteLine("download complete!");
Console.Write($"Extracting {dbFileName} .... ");
ZipFile.ExtractToDirectory(dbFileName, ".", true);
Console.WriteLine("extraction complete!");
Console.Write($"Deleting {dbFileName} .... ");
File.Delete(dbFileName);
Console.WriteLine("Deleted!");
var sqlFile = dbFileName.Substring(0, dbFileName.Length - 4);
Console.Write($"Importing {sqlFile} into SQL server at {config.MySql.World.Host}:{config.MySql.World.Port} (This will take a while, please be patient) .... ");
using (var sr = File.OpenText(sqlFile))
{
var sqlConnect = new MySql.Data.MySqlClient.MySqlConnection($"server={config.MySql.World.Host};port={config.MySql.World.Port};user={config.MySql.World.Username};preplacedword={config.MySql.World.Preplacedword};DefaultCommandTimeout=120");
var line = string.Empty;
var completeSQLline = string.Empty;
while ((line = sr.ReadLine()) != null)
{
//do minimal amount of work here
if (line.EndsWith(";"))
{
completeSQLline += line + Environment.NewLine;
var script = new MySql.Data.MySqlClient.MySqlScript(sqlConnect, completeSQLline);
try
{
script.StatementExecuted += new MySql.Data.MySqlClient.MySqlStatementExecutedEventHandler(OnStatementExecutedOutputDot);
var count = script.Execute();
}
catch (MySql.Data.MySqlClient.MySqlException)
{
}
completeSQLline = string.Empty;
}
else
completeSQLline += line + Environment.NewLine;
}
}
Console.WriteLine(" complete!");
Console.Write($"Deleting {sqlFile} .... ");
File.Delete(sqlFile);
Console.WriteLine("Deleted!");
}
Console.WriteLine("exiting setup for ACEmulator.");
}
19
Source : Program_DbUpdates.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
private static void UpdateToLatestWorldDatabase(string dbURL, string dbFileName)
{
Console.WriteLine();
if (IsRunningInContainer)
{
Console.WriteLine(" ");
Console.WriteLine("This process will take a while, depending on many factors, and may look stuck while reading and importing the world database, please be patient! ");
Console.WriteLine(" ");
}
Console.Write($"Downloading {dbFileName} .... ");
using (var client = new WebClient())
{
try
{
client.DownloadFile(dbURL, dbFileName);
}
catch
{
Console.Write($"Download for {dbFileName} failed!");
return;
}
}
Console.WriteLine("download complete!");
Console.Write($"Extracting {dbFileName} .... ");
ZipFile.ExtractToDirectory(dbFileName, ".", true);
Console.WriteLine("extraction complete!");
Console.Write($"Deleting {dbFileName} .... ");
File.Delete(dbFileName);
Console.WriteLine("Deleted!");
var sqlFile = dbFileName.Substring(0, dbFileName.Length - 4);
Console.Write($"Importing {sqlFile} into SQL server at {ConfigManager.Config.MySql.World.Host}:{ConfigManager.Config.MySql.World.Port} (This will take a while, please be patient) .... ");
using (var sr = File.OpenText(sqlFile))
{
var sqlConnect = new MySql.Data.MySqlClient.MySqlConnection($"server={ConfigManager.Config.MySql.World.Host};port={ConfigManager.Config.MySql.World.Port};user={ConfigManager.Config.MySql.World.Username};preplacedword={ConfigManager.Config.MySql.World.Preplacedword};DefaultCommandTimeout=120");
var line = string.Empty;
var completeSQLline = string.Empty;
var dbname = ConfigManager.Config.MySql.World.Database;
while ((line = sr.ReadLine()) != null)
{
line = line.Replace("ace_world", dbname);
//do minimal amount of work here
if (line.EndsWith(";"))
{
completeSQLline += line + Environment.NewLine;
var script = new MySql.Data.MySqlClient.MySqlScript(sqlConnect, completeSQLline);
try
{
script.StatementExecuted += new MySql.Data.MySqlClient.MySqlStatementExecutedEventHandler(OnStatementExecutedOutputDot);
var count = script.Execute();
}
catch (MySql.Data.MySqlClient.MySqlException)
{
}
completeSQLline = string.Empty;
}
else
completeSQLline += line + Environment.NewLine;
}
}
Console.WriteLine(" complete!");
Console.Write($"Deleting {sqlFile} .... ");
File.Delete(sqlFile);
Console.WriteLine("Deleted!");
}
19
Source : ProjectConfig.cs
with MIT License
from adamant
with MIT License
from adamant
public static ProjectConfig Load(string path)
{
var extension = Path.GetExtension(path);
string projectFilePath;
if (Directory.Exists(path))
{
projectFilePath = Path.Combine(path, FileName);
}
else if (extension == "vson")
{
projectFilePath = path;
}
else
{
throw new Exception($"Unexpected project file extension '.{extension}'");
}
projectFilePath = Path.GetFullPath(projectFilePath);
using var file = new JsonTextReader(File.OpenText(projectFilePath));
var serializer = new JsonSerializer();
var projectFile = serializer.Deserialize<ProjectConfig>(file) ?? throw new NullReferenceException();
projectFile.FullPath = projectFilePath;
return projectFile;
}
19
Source : UpdateManager.cs
with MIT License
from admaiorastudio
with MIT License
from admaiorastudio
private void KillRunningProcesses()
{
if (File.Exists(_processDatFilePath))
{
using (var s = File.OpenText(_processDatFilePath))
{
int processId = 0;
try
{
while(!s.EndOfStream)
{
processId = Int32.Parse(s.ReadLine());
if (processId == 0)
continue;
var process = Process.GetProcessById(processId);
if (process != null && !process.HasExited)
process.Kill();
}
}
catch (Exception ex)
{
if (processId != 0)
System.Diagnostics.Debug.WriteLine($"RealXaml was unable to kill process with id {processId}");
System.Diagnostics.Debug.WriteLine(ex);
}
}
}
}
19
Source : FileUtil.cs
with MIT License
from adospace
with MIT License
from adospace
public static async Task<string> ReadAllTextFileAsync(string filename)
{
using (var reader = File.OpenText(filename))
{
return await reader.ReadToEndAsync();
}
}
19
Source : Extensions.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public static TextReader OpenText(this RetryPolicy retryPolicy, string path)
{
return retryPolicy.ExecuteAction(() => File.OpenText(path));
}
19
Source : CrmJsonConvert.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public static object DeserializeFile(string path)
{
using (var reader = System.IO.File.OpenText(path))
using (var jtr = new JsonTextReader(reader))
{
var serializer = JsonSerializer.Create(SerializerSettings);
var value = serializer.Deserialize(jtr);
return value;
}
}
19
Source : AElfKeyStore.cs
with MIT License
from AElfProject
with MIT License
from AElfProject
public async Task<ECKeyPair> ReadKeyPairAsync(string address, string preplacedword)
{
try
{
var keyFilePath = GetKeyFileFullPath(address);
var privateKey = await Task.Run(() =>
{
using (var textReader = File.OpenText(keyFilePath))
{
var json = textReader.ReadToEnd();
return _keyStoreService.DecryptKeyStoreFromJson(preplacedword, json);
}
});
return CryptoHelper.FromPrivateKey(privateKey);
}
catch (FileNotFoundException ex)
{
throw new KeyStoreNotFoundException("Keystore file not found.", ex);
}
catch (DirectoryNotFoundException ex)
{
throw new KeyStoreNotFoundException("Invalid keystore path.", ex);
}
catch (DecryptionException ex)
{
throw new InvalidPreplacedwordException("Invalid preplacedword.", ex);
}
}
19
Source : JSONParser.cs
with MIT License
from AgileoAutomation
with MIT License
from AgileoAutomation
public List<ComponentSpecification> BuildSpecifications(string filepath)
{
try
{
reader = File.OpenText(filepath);
serializer = new JsonSerializer();
}
catch
{
MessageBox.Show("The specifications file is open in a other process");
return null;
}
try
{
List<ComponentSpecification> specs = (List<ComponentSpecification>)serializer.Deserialize(reader, typeof(List<ComponentSpecification>));
return specs;
}
catch (Exception e)
{
MessageBox.Show("Invalid specifications file :\nPlease you must give at least an replacedembly or a subcomponent by component");
return null;
}
}
19
Source : ConnectCamera.xaml.cs
with MIT License
from AlexBrochu
with MIT License
from AlexBrochu
private void LoadConnexion()
{
listBox_saved.Items.Clear();
if (!File.Exists(path_to_connexion_file))
{
File.CreateText(path_to_connexion_file).Close();
}
using (StreamReader file = File.OpenText(path_to_connexion_file))
{
JsonSerializer serializer = new JsonSerializer();
cameras = (List<CameraConnexion>)serializer.Deserialize(file, typeof(List<CameraConnexion>));
if (cameras != null)
{
foreach (CameraConnexion cam in cameras)
{
listBox_saved.Items.Add(cam.CameraName);
}
}
}
}
19
Source : ConfigLoader.cs
with MIT License
from alexis-
with MIT License
from alexis-
public static async Task<T> SafeLoadJson<T>(string filePath)
{
if (filePath != null && File.Exists(filePath))
using (var reader = File.OpenText(filePath))
return JsonConvert.DeserializeObject<T>(await reader.ReadToEndAsync());
return default(T);
}
19
Source : DnsClient.cs
with Apache License 2.0
from alexreinert
with Apache License 2.0
from alexreinert
public static List<IPAddress> GetLocalConfiguredDnsServers()
{
List<IPAddress> res = new List<IPAddress>();
try
{
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
if ((nic.OperationalStatus == OperationalStatus.Up) && (nic.NetworkInterfaceType != NetworkInterfaceType.Loopback))
{
foreach (IPAddress dns in nic.GetIPProperties().DnsAddresses)
{
// only use servers defined in draft-ietf-ipngwg-dns-discovery if they are in the same subnet
// fec0::/10 is marked deprecated in RFC 3879, so nobody should use these addresses
if (dns.AddressFamily == AddressFamily.InterNetworkV6)
{
IPAddress unscoped = new IPAddress(dns.GetAddressBytes());
if (unscoped.Equals(IPAddress.Parse("fec0:0:0:ffff::1"))
|| unscoped.Equals(IPAddress.Parse("fec0:0:0:ffff::2"))
|| unscoped.Equals(IPAddress.Parse("fec0:0:0:ffff::3")))
{
if (!nic.GetIPProperties().UnicastAddresses.Any(x => x.Address.GetNetworkAddress(10).Equals(IPAddress.Parse("fec0::"))))
continue;
}
}
if (!res.Contains(dns))
res.Add(dns);
}
}
}
}
catch (Exception e)
{
Trace.TraceError("Configured nameserver couldn't be determined: " + e);
}
// try parsing resolv.conf since getting data by NetworkInterface is not supported on non-windows mono
if ((res.Count == 0) && ((Environment.OSVersion.Platform == PlatformID.Unix) || (Environment.OSVersion.Platform == PlatformID.MacOSX)))
{
try
{
using (StreamReader reader = File.OpenText("/etc/resolv.conf"))
{
string line;
while ((line = reader.ReadLine()) != null)
{
int commentStart = line.IndexOf('#');
if (commentStart != -1)
{
line = line.Substring(0, commentStart);
}
string[] lineData = line.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
IPAddress dns;
if ((lineData.Length == 2) && (lineData[0] == "nameserver") && (IPAddress.TryParse(lineData[1], out dns)))
{
res.Add(dns);
}
}
}
}
catch (Exception e)
{
Trace.TraceError("/etc/resolv.conf could not be parsed: " + e);
}
}
if (res.Count == 0)
{
// fallback: use the public dns-resolvers of google
res.Add(IPAddress.Parse("2001:4860:4860::8844"));
res.Add(IPAddress.Parse("2001:4860:4860::8888"));
res.Add(IPAddress.Parse("8.8.4.4"));
res.Add(IPAddress.Parse("8.8.8.8"));
}
return res.OrderBy(x => x.AddressFamily == AddressFamily.InterNetworkV6 ? 1 : 0).ToList();
}
19
Source : Utils.cs
with Apache License 2.0
from Algoryx
with Apache License 2.0
from Algoryx
public static string[] ParseColladareplacedetElement( string colladaFilename, int maxNumLines = 50 )
{
List<string> replacedetElement = null;
try {
using ( var stream = System.IO.File.OpenText( colladaFilename ) ) {
var line = string.Empty;
var lineNumber = 0;
while ( ++lineNumber <= maxNumLines && (line = stream.ReadLine()) != null ) {
if ( replacedetElement == null && line.TrimStart().StartsWith( "<replacedet>" ) ) {
replacedetElement = new List<string>();
replacedetElement.Add( line );
}
else if ( replacedetElement != null && line.TrimStart().StartsWith( "</replacedet>" ) ) {
replacedetElement.Add( line );
break;
}
else if ( replacedetElement != null )
replacedetElement.Add( line );
}
}
}
catch {
replacedetElement?.Clear();
}
return replacedetElement?.ToArray();
}
19
Source : IntegrationTests.cs
with Apache License 2.0
from allure-framework
with Apache License 2.0
from allure-framework
private void ParseAllureSuites(string allureResultsDir)
{
var allureTestResultFiles = new DirectoryInfo(allureResultsDir).GetFiles("*-result.json");
var allureContainerFiles = new DirectoryInfo(allureResultsDir).GetFiles("*-container.json");
var serializer = new JsonSerializer();
foreach (var fileInfo in allureContainerFiles)
{
using var file = File.OpenText(fileInfo.FullName);
var container = (TestResultContainer)serializer.Deserialize(file, typeof(TestResultContainer));
allureContainers.Add(container);
}
foreach (var fileInfo in allureTestResultFiles)
{
using var file = File.OpenText(fileInfo.FullName);
var testResult = (TestResult)serializer.Deserialize(file, typeof(TestResult));
allureTestResults.Add(testResult);
}
}
19
Source : CSVReader.cs
with GNU Lesser General Public License v3.0
from Alois-xx
with GNU Lesser General Public License v3.0
from Alois-xx
public List<KeyValuePair<Dictionary<string, ProcessTypeInfo>,VMMapData>> Parse()
{
var lret = new List<KeyValuePair<Dictionary<string, ProcessTypeInfo>, VMMapData>>();
using (var file = File.OpenText(_File))
{
ProcessContextInfo currentProcess = new ProcessContextInfo();
string line = null;
bool bFirst = true;
RowData rowData = new RowData();
VMMapProcessData currentVMMap = new VMMapProcessData();
var currentTypeMap = new Dictionary<string, ProcessTypeInfo>();
while ( (line= file.ReadLine()) != null )
{
if( bFirst )
{
// get column separator if present
if( line.StartsWith(SepLine) && line.Length == SepLine.Length+1)
{
Seps[0] = line[SepLine.Length];
continue;
}
// get column names
ColumnNames = line.Split(Seps);
CreateParser(ColumnNames);
bFirst = false;
continue;
}
// get columns
var parts = line.Split(Seps);
// parse CSV columns into intermediate row object
ParseColumns(parts, rowData);
if( currentProcess.Pid != rowData.ProcessContext.Pid)
{
if (currentProcess.Pid != 0)
{
lret.Add(new KeyValuePair<Dictionary<string, ProcessTypeInfo>, VMMapData>(currentTypeMap, ReturnNullIfNoDataPresent(currentVMMap)));
currentTypeMap = new Dictionary<string, ProcessTypeInfo>();
currentVMMap = new VMMapProcessData();
}
currentProcess = rowData.ProcessContext;
}
if(VMMapRows.Contains(rowData.Type))
{
currentVMMap.Add(rowData.Type, rowData.AllocatesBytes);
}
else
{
currentTypeMap.Add(rowData.Type, new ProcessTypeInfo(currentProcess)
{
Name = rowData.Type,
AllocatedSizeInBytes = rowData.AllocatesBytes,
Count = rowData.Instances
});
}
}
lret.Add(new KeyValuePair<Dictionary<string, ProcessTypeInfo>, VMMapData>(currentTypeMap, ReturnNullIfNoDataPresent(currentVMMap)));
}
return lret;
}
19
Source : frmMain.cs
with GNU General Public License v3.0
from amakvana
with GNU General Public License v3.0
from amakvana
private void BtnCheck_Click(object sender, EventArgs e)
{
ToggleControls(false);
// read in current version
// get latest version
// compare
if (!string.IsNullOrWhiteSpace(txtYuzuLocation.Text))
{
string yuzuLocation = txtYuzuLocation.Text;
if (File.Exists(yuzuLocation + "\\version"))
{
// get current version
string currentVersion = "";
string latestVersion = "";
using (StreamReader sr = File.OpenText(yuzuLocation + "\\version"))
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
currentVersion = s;
}
}
// get latest version from repo
using (var wc = new WebClient())
{
// fetch latest Yuzu release
string repo = "https://github.com/yuzu-emu/yuzu-mainline/releases/latest";
string repoHtml = wc.DownloadString(repo);
Regex r = new Regex(@"(?:\/yuzu-emu\/yuzu-mainline\/releases\/download\/[^""]+)");
foreach (Match m in r.Matches(repoHtml))
{
string url = m.Value.Trim();
if (url.Contains(".zip") && !url.Contains("debugsymbols"))
{
latestVersion = url.Split('/')[5].Trim().Remove(0, 11);
}
}
}
// compare & tell user
string message = (currentVersion == latestVersion) ? "You have the latest version of Yuzu!" : "Update available, please select Yuzu from the dropdown and click Update";
MessageBox.Show(message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Failed to get version, please select Yuzu from the dropdown and click Update", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
MessageBox.Show("Please select your Yuzu root folder", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
// enable relevant buttons
ToggleControls(true);
if (cboOptions.SelectedIndex == 0 && DependenciesInstalled())
{
btnProcess.Enabled = false;
btnProcess.Text = "Installed";
}
}
19
Source : ObjImporter.cs
with MIT License
from amazingalek
with MIT License
from amazingalek
private static void PopulateMeshStruct(ref MeshStruct mesh)
{
var stream = File.OpenText(mesh.FileName);
var entireText = stream.ReadToEnd();
stream.Close();
using var reader = new StringReader(entireText);
var currentText = reader.ReadLine();
char[] splitIdentifier = { ' ' };
char[] splitIdentifier2 = { '/' };
var f = 0;
var f2 = 0;
var v = 0;
var vn = 0;
var vt = 0;
var vt1 = 0;
var vt2 = 0;
while (currentText != null)
{
if (!currentText.StartsWith("f ") &&
!currentText.StartsWith("v ") &&
!currentText.StartsWith("vt ") &&
!currentText.StartsWith("vn ") &&
!currentText.StartsWith("g ") &&
!currentText.StartsWith("usemtl ") &&
!currentText.StartsWith("mtllib ") &&
!currentText.StartsWith("vt1 ") &&
!currentText.StartsWith("vt2 ") &&
!currentText.StartsWith("vc ") &&
!currentText.StartsWith("usemap "))
{
currentText = reader.ReadLine();
currentText = currentText?.Replace(" ", " ");
}
else
{
currentText = currentText.Trim();
var brokenString = currentText.Split(splitIdentifier, 50);
switch (brokenString[0])
{
case "v":
mesh.Vertices[v] = new Vector3(
System.Convert.ToSingle(brokenString[1]), System.Convert.ToSingle(brokenString[2]),
System.Convert.ToSingle(brokenString[3]));
v++;
break;
case "vt":
mesh.Uv[vt] = new Vector2(
System.Convert.ToSingle(brokenString[1]),
System.Convert.ToSingle(brokenString[2]));
vt++;
break;
case "vt1":
mesh.Uv[vt1] = new Vector2(
System.Convert.ToSingle(brokenString[1]),
System.Convert.ToSingle(brokenString[2]));
vt1++;
break;
case "vt2":
mesh.Uv[vt2] = new Vector2(
System.Convert.ToSingle(brokenString[1]),
System.Convert.ToSingle(brokenString[2]));
vt2++;
break;
case "vn":
mesh.Normals[vn] = new Vector3(
System.Convert.ToSingle(brokenString[1]),
System.Convert.ToSingle(brokenString[2]),
System.Convert.ToSingle(brokenString[3]));
vn++;
break;
case "f":
var j = 1;
var intArray = new List<int>();
while (j < brokenString.Length && ("" + brokenString[j]).Length > 0)
{
var temp = new Vector3();
var brokenBrokenString = brokenString[j].Split(splitIdentifier2, 3);
temp.x = System.Convert.ToInt32(brokenBrokenString[0]);
if (brokenBrokenString.Length > 1) // Some .obj files skip UV and normal
{
if (brokenBrokenString[1] != "") // Some .obj files skip the uv and not the normal
{
temp.y = System.Convert.ToInt32(brokenBrokenString[1]);
}
temp.z = System.Convert.ToInt32(brokenBrokenString[2]);
}
j++;
mesh.FaceData[f2] = temp;
intArray.Add(f2);
f2++;
}
j = 1;
while (j + 2 < brokenString.Length) // Create triangles out of the face data. There will generally be more than 1 triangle per face.
{
mesh.Triangles[f] = intArray[0];
f++;
mesh.Triangles[f] = intArray[j];
f++;
mesh.Triangles[f] = intArray[j + 1];
f++;
j++;
}
break;
}
currentText = reader.ReadLine();
currentText = currentText?.Replace(" ", " "); // Some .obj files insert double spaces, this removes them.
}
}
}
19
Source : ObjImporter.cs
with MIT License
from amazingalek
with MIT License
from amazingalek
private static MeshStruct CreateMeshStruct(string filename)
{
var triangles = 0;
var vertices = 0;
var vt = 0;
var vn = 0;
var face = 0;
var stream = File.OpenText(filename);
var entireText = stream.ReadToEnd();
stream.Close();
using var reader = new StringReader(entireText);
var currentText = reader.ReadLine();
char[] splitIdentifier = { ' ' };
while (currentText != null)
{
if (!currentText.StartsWith("f ")
&& !currentText.StartsWith("v ")
&& !currentText.StartsWith("vt ")
&& !currentText.StartsWith("vn "))
{
currentText = reader.ReadLine();
currentText = currentText?.Replace(" ", " ");
}
else
{
currentText = currentText.Trim();
var brokenString = currentText.Split(splitIdentifier, 50);
switch (brokenString[0])
{
case "v":
vertices++;
break;
case "vt":
vt++;
break;
case "vn":
vn++;
break;
case "f":
face = face + brokenString.Length - 1;
triangles += 3 * (brokenString.Length - 2);
/* brokenString.Length is 3 or greater since a face must have at least
3 vertices. For each additional vertex, there is an additional
triangle in the mesh (hence this formula).*/
break;
}
currentText = reader.ReadLine();
currentText = currentText?.Replace(" ", " ");
}
}
return new MeshStruct
{
FileName = filename,
Triangles = new int[triangles],
Vertices = new Vector3[vertices],
Uv = new Vector2[vt],
Normals = new Vector3[vn],
FaceData = new Vector3[face]
};
}
19
Source : OptionsService.cs
with MIT License
from AntonyCorbett
with MIT License
from AntonyCorbett
private Options ReadOptions()
{
if (_optionsFilePath == null || !File.Exists(_optionsFilePath))
{
return WriteDefaultOptions();
}
using (var file = File.OpenText(_optionsFilePath))
{
var serializer = new JsonSerializer();
var result = (Options?)serializer.Deserialize(file, typeof(Options));
result?.Sanitize();
SetCulture(result?.Culture);
return result ?? WriteDefaultOptions();
}
}
19
Source : OptionsService.cs
with MIT License
from AntonyCorbett
with MIT License
from AntonyCorbett
private void ReadOptions()
{
if (!File.Exists(_optionsFilePath))
{
WriteDefaultOptions();
}
else
{
using (StreamReader file = File.OpenText(_optionsFilePath))
{
JsonSerializer serializer = new JsonSerializer();
_options = (Options)serializer.Deserialize(file, typeof(Options));
}
}
}
19
Source : OptionsService.cs
with MIT License
from AntonyCorbett
with MIT License
from AntonyCorbett
private void ReadOptions()
{
if (_optionsFilePath == null || !File.Exists(_optionsFilePath))
{
WriteDefaultOptions();
return;
}
using var file = File.OpenText(_optionsFilePath);
var serializer = new JsonSerializer();
_options = (Options?)serializer.Deserialize(file, typeof(Options));
if (_options != null)
{
SetMidWeekOrWeekend();
ResetCircuitVisit();
_options.Sanitize();
CommandLineMonitorOverride();
SetCulture();
}
}
19
Source : OptionsService.cs
with MIT License
from AntonyCorbett
with MIT License
from AntonyCorbett
private Options? ReadOptions()
{
if (_optionsFilePath == null || !File.Exists(_optionsFilePath))
{
return WriteDefaultOptions();
}
using var file = File.OpenText(_optionsFilePath);
var serializer = new JsonSerializer();
var result = (Options?)serializer.Deserialize(file, typeof(Options));
result?.Sanitize();
SetCulture(result?.Culture);
return result;
}
19
Source : OptionsService.cs
with MIT License
from AntonyCorbett
with MIT License
from AntonyCorbett
private bool ReadOptionsInternal()
{
if (string.IsNullOrEmpty(_optionsFilePath))
{
return false;
}
using var file = File.OpenText(_optionsFilePath);
var serializer = new JsonSerializer();
var options = (Options?)serializer.Deserialize(file, typeof(Options));
if (options == null)
{
return false;
}
Options = options;
return true;
}
19
Source : OptionsService.cs
with MIT License
from AntonyCorbett
with MIT License
from AntonyCorbett
private void ReadOptions()
{
if (!File.Exists(_optionsFilePath))
{
WriteDefaultOptions();
}
else
{
using (var file = File.OpenText(_optionsFilePath))
{
var serializer = new JsonSerializer();
_options = (AppOptions.Options)serializer.Deserialize(file, typeof(AppOptions.Options));
_options.Sanitize();
SetCulture();
}
}
}
19
Source : ProjectScanner.cs
with MIT License
from atakansarioglu
with MIT License
from atakansarioglu
private static bool ScanSingleFile(string fileName, ref BBCodeBase bbCodeBase)
{
try
{
// Open the file as text.
StreamReader sr = File.OpenText(fileName);
// Iterate all lines until the end.
string lineText;
int lineNumber = 0;
while (!sr.EndOfStream)
{
// Read single line.
lineText = sr.ReadLine();
lineNumber++;
// Try to parse the line with descriptor parser. Result is not null if successful.
BBCodeObject bbCode = BBCodeDescriptorParser.Parse(lineText, fileName, lineNumber);
// Add to the database (only if not null).
bbCodeBase.AddBBCode(bbCode);
}
// Close the file.
sr.Close();
// Everything is OK.
return true;
}
catch { }
// Problem occured.
return false;
}
19
Source : Chart.cs
with MIT License
from audfx
with MIT License
from audfx
public static KshChart CreateFromFile(string fileName)
{
using var reader = File.OpenText(fileName);
return Create(fileName, reader);
}
19
Source : CustomChartTypeScanner.cs
with MIT License
from audfx
with MIT License
from audfx
private void ConvertAction()
{
string chartsDir = Path.GetFullPath(TheoriConfig.ChartsDirectory);
if (!Directory.Exists(chartsDir)) return;
var setSer = new ChartSetSerializer(chartsDir);
while (true)
{
while (m_queue.IsEmpty)
{
Thread.Sleep(500);
m_attempts++;
if (m_attempts > 15) return;
}
if (!m_queue.TryDequeue(out var entry))
{
m_attempts++;
continue;
}
var (setDir, charts) = entry;
var sets = setDir.GetFiles("*.theori-set");
if (sets.Length == 0)
{
var setInfo = new ChartSetInfo()
{
FileName = "ksh-auto.theori-set",
FilePath = PathL.RelativePath(chartsDir, setDir.FullName),
};
foreach (var chartFile in charts)
{
using var reader = File.OpenText(chartFile.FullName);
var meta = KshChartMetadata.Create(reader);
var chartInfo = new ChartInfo()
{
Set = setInfo,
GameMode = NeuroSonicGameMode.Instance,
FileName = chartFile.Name,
Songreplacedle = meta.replacedle,
SongArtist = meta.Artist,
SongFileName = meta.MusicFile ?? meta.MusicFileNoFx ?? "??",
SongVolume = meta.MusicVolume,
ChartOffset = meta.OffsetMillis / 1000.0,
Charter = meta.EffectedBy,
JacketFileName = meta.JacketPath,
JacketArtist = meta.Illustrator,
BackgroundFileName = meta.Background,
BackgroundArtist = "Unknown",
DifficultyLevel = meta.Level,
DifficultyIndex = meta.Difficulty.ToDifficultyIndex(chartFile.Name),
DifficultyName = meta.Difficulty.ToDifficultyString(chartFile.Name),
DifficultyNameShort = meta.Difficulty.ToShortString(chartFile.Name),
DifficultyColor = meta.Difficulty.GetColor(chartFile.Name),
};
setInfo.Charts.Add(chartInfo);
}
try
{
setSer.SaveToFile(setInfo);
ChartDatabaseService.AddSet(setInfo);
}
catch (Exception e)
{
Logger.Log(e.Message);
string setFile = Path.Combine(chartsDir, setInfo.FilePath, "ksh-auto.theori-set");
if (File.Exists(setFile)) File.Delete(setFile);
}
}
else
{
//Logger.Log(".theori-set file already exists, skipping.");
// currently replacedume everything is fine, eventually parse and check for new chart files
}
}
}
19
Source : CustomLocaleLoader.cs
with MIT License
from Auros
with MIT License
from Auros
public async Task LoadLocales()
{
var folder = Path.Combine(UnityGame.UserDataPath, "SIRA", "Localizations");
if (!Directory.Exists(folder))
{
Directory.CreateDirectory(folder);
}
var files = new DirectoryInfo(folder).EnumerateFiles().Where(x => x.Extension == ".csv" || x.Extension == ".tsv");
for (int i = 0; i < files.Count(); i++)
{
var file = files.ElementAt(i);
using (var reader = File.OpenText(file.FullName))
{
var fileText = await reader.ReadToEndAsync();
_localizer.AddLocalizationSheet(fileText, file.Extension.EndsWith("csv") ? GoogleDriveDownloadFormat.CSV : GoogleDriveDownloadFormat.TSV, file.FullName);
}
}
}
19
Source : IPCadapterDBus.cs
with MIT License
from automuteus
with MIT License
from automuteus
private Task CleanPid()
{
// Make sure the pidfile is cleaned up if we have one.
var pidfile = Path.Join(Settings.StorageLocation, ".amonguscapture.pid");
if (File.Exists(pidfile))
{
int pid;
bool fileread;
using (var pidread = File.OpenText(Path.Join(Settings.StorageLocation, ".amonguscapture.pid")))
{
fileread = Int32.TryParse(pidread.ReadLine(), out pid);
}
if (!fileread)
{
// Bad read, file must be corrupt. Clear pidfile.
File.Delete(pidfile);
}
if (pid == Process.GetCurrentProcess().Id)
{
// This is our process. Delete file.
File.Delete(pidfile);
}
}
return Task.CompletedTask;
}
19
Source : IPCadapterDBus.cs
with MIT License
from automuteus
with MIT License
from automuteus
public override URIStartResult HandleURIStart(string[] args)
{
var myProcessId = Process.GetCurrentProcess().Id;
//Process[] processes = Process.GetProcessesByName("AmongUsCapture");
//Process[] dotnetprocesses = Process.GetProcessesByName("dotnet");
//foreach (Process p in processes)
//{
//if (p.Id != myProcessId)
// {
// p.Kill();
// }
// }
Console.WriteLine(Program.GetExecutablePath());
//mutex = new Mutex(true, appName, out var createdNew);
_isHostInstance = false;
var wasURIStart = args.Length > 0 && args[0].StartsWith(UriScheme + "://");
var result = URIStartResult.CONTINUE;
if (!File.Exists(Path.Join(Settings.StorageLocation, ".amonguscapture.pid")))
{
_isHostInstance = true;
}
else
{
// Open our PID file.
using (var pidfile = File.OpenText(Path.Join(Settings.StorageLocation, ".amonguscapture.pid")))
{
var pid = pidfile.ReadLine();
if (pid != null)
{
var pidint = Int32.Parse(pid);
try
{
var capproc = Process.GetProcessById(pidint);
var iscapture = false;
foreach (ProcessModule mod in capproc.Modules)
{
// If we find amonguscapturedll in the modules, we can be certain
// that the located pid is, in fact, an AmongUsCapture process.
if (mod.ModuleName == Process.GetCurrentProcess().MainModule.ModuleName)
{
iscapture = true;
break;
}
}
if (!iscapture || capproc.HasExited)
throw new ArgumentException();
}
catch (ArgumentException e)
{
// Process doesn't exist. Clear the file.
Console.WriteLine($"Found stale PID file containing {pid}.");
File.Delete(Path.Join(Settings.StorageLocation, ".amonguscapture.pid"));
_isHostInstance = true;
}
}
}
}
if (_isHostInstance)
{
using (var pidwriter = File.CreateText(Path.Join(Settings.StorageLocation, ".amonguscapture.pid")))
{
pidwriter.Write(myProcessId);
}
}
if (!_isHostInstance) // send it to already existing instance if applicable, then close
{
if (wasURIStart) SendToken(args[0]).Wait();
return URIStartResult.CLOSE;
}
else if (wasURIStart) // URI start on new instance, continue as normal but also handle current argument
{
result = URIStartResult.PARSE;
}
RegisterProtocol();
return result;
}
19
Source : CodeGenExecutor.cs
with MIT License
from Avanade
with MIT License
from Avanade
private async Task<(List<CodeGenScriptArgs> Scripts, ConfigType ConfigType, List<IConfigEditor> ConfigEditors)> LoadScriptConfigAsync(FileInfo scriptFile)
{
var list = new List<CodeGenScriptArgs>();
var editors = new List<IConfigEditor>();
// Load the script XML content.
XElement xmlScript;
if (scriptFile!.Exists)
{
using var fs = File.OpenText(scriptFile.FullName);
xmlScript = await XElement.LoadAsync(fs, LoadOptions.None, CancellationToken.None).ConfigureAwait(false);
}
else
{
var c = await ResourceManager.GetScriptContentAsync(scriptFile.Name, _args.replacedemblies.ToArray()).ConfigureAwait(false);
if (c == null)
throw new CodeGenException($"The Script XML '{scriptFile.Name}' does not exist (either as a file or as an embedded resource).");
xmlScript = XElement.Parse(c);
}
if (xmlScript?.Name != "Script")
throw new CodeGenException($"The Script XML '{scriptFile.Name}' must have a root element named 'Script'.");
var ct = xmlScript.Attribute("ConfigType")?.Value ?? throw new CodeGenException($"The Script XML file '{scriptFile.FullName}' must have an attribute named 'ConfigType' within the root 'Script' element.");
if (!Enum.TryParse<ConfigType>(ct, true, out var configType))
throw new CodeGenException($"The Script XML '{scriptFile.Name}' attribute named 'ConfigType' has an invalid value '{ct}'.");
var ia = xmlScript.Attribute("Inherits")?.Value;
if (ia != null)
{
foreach (var ian in ia.Split(';', StringSplitOptions.RemoveEmptyEntries))
{
var fi = new FileInfo(Path.Combine(scriptFile.DirectoryName, ian.Trim()));
var result = await LoadScriptConfigAsync(fi).ConfigureAwait(false);
if (result.ConfigType != configType)
throw new CodeGenException($"The Script XML '{scriptFile.Name}' inherits '{fi.FullName}' which has a different 'ConfigType'; this must be the same.");
list.AddRange(result.Scripts);
editors.AddRange(result.ConfigEditors);
}
}
var ce = xmlScript.Attribute("ConfigEditor")?.Value;
if (ce != null)
{
var t = Type.GetType(ce, false);
if (t == null)
throw new CodeGenException($"The Script XML '{scriptFile.Name}' references CodeEditor Type '{ce}' which could not be found/loaded.");
if (!typeof(IConfigEditor).IsreplacedignableFrom(t))
throw new CodeGenException($"The Script XML '{scriptFile.Name}' references CodeEditor Type '{ce}' which does not implement IConfigEditor.");
editors.Add((IConfigEditor)(Activator.CreateInstance(t) ?? throw new CodeGenException($"The Script XML '{scriptFile.Name}' references CodeEditor Type '{ce}' which could not be instantiated.")));
}
if (ia == null && !xmlScript.Elements("Generate").Any())
throw new CodeGenException($"The Script XML '{scriptFile.Name}' file must have at least a single 'Generate' element.");
foreach (var scriptEle in xmlScript.Elements("Generate"))
{
var args = new CodeGenScriptArgs();
foreach (var att in scriptEle.Attributes())
{
switch (att.Name.LocalName)
{
case "GenType": args.GenType = att.Value; break;
case "FileName": args.FileName = att.Value; break;
case "Template": args.Template = att.Value; break;
case "OutDir": args.OutDir = att.Value; break;
case "GenOnce": args.GenOnce = string.Compare(att.Value, "true", true) == 0; break;
case "HelpText": args.HelpText = att.Value; break;
default: args.OtherParameters.Add(att.Name.LocalName, att.Value); break;
}
}
list.Add(args);
}
return (list, configType, editors);
}
19
Source : LambdaPackager.cs
with Apache License 2.0
from aws
with Apache License 2.0
from aws
private static bool FileIsLinuxShellScript(string filePath)
{
using (var sr = File.OpenText(filePath))
{
while (!sr.EndOfStream)
{
var line = sr.ReadLine().Trim();
if (line.Length > 0)
{
return line.StartsWith(Shebang);
}
}
}
return false;
}
19
Source : SdkVersionsUtils.cs
with Apache License 2.0
from aws
with Apache License 2.0
from aws
internal static JObject ReadSdkVersionFile(string sdkreplacedembliesFolder)
{
var versionsFilePath = Path.Combine(sdkreplacedembliesFolder, "..", "_sdk-versions.json");
try
{
using (var jsonReader = new JsonTextReader(File.OpenText(versionsFilePath)))
{
return JObject.Load(jsonReader);
}
}
catch (Exception e)
{
throw new Exception($"Error while reading from {versionsFilePath}", e);
}
}
19
Source : Program.cs
with Apache License 2.0
from aws
with Apache License 2.0
from aws
private string GetSDKVersion(string versionFilePath)
{
using (StreamReader reader = File.OpenText(versionFilePath))
{
JObject jsonRoot = (JObject)JToken.ReadFrom(new JsonTextReader(reader));
return jsonRoot["ProductVersion"].Value<string>();
}
}
19
Source : FileDownloader.cs
with Apache License 2.0
from awslabs
with Apache License 2.0
from awslabs
public async Task<string> ReadFilereplacedtringAsync(string url)
{
string path = ConvertFileUrlToPath(url);
using (var reader = File.OpenText(path))
{
return await reader.ReadToEndAsync();
}
}
19
Source : PackageVersionValidator.cs
with Apache License 2.0
from awslabs
with Apache License 2.0
from awslabs
public bool ValidatePackageVersion (string filePath, out IList<string> messages)
{
using (StreamReader packageaVersionReader = File.OpenText(filePath))
using (JsonTextReader jsonReader = new JsonTextReader(packageaVersionReader))
{
JToken token = JToken.ReadFrom(new JsonTextReader(packageaVersionReader));
return token.IsValid(_schema, out messages);
}
}
19
Source : FileDeviceIdComponent.cs
with Apache License 2.0
from awslabs
with Apache License 2.0
from awslabs
public string GetValue()
{
foreach (var path in _paths)
{
if (!File.Exists(path))
{
continue;
}
try
{
var contents = default(string);
using (var file = File.OpenText(path))
{
contents = file.ReadToEnd();
}
contents = contents.Trim();
return contents;
}
catch (UnauthorizedAccessException)
{
}
}
return string.Empty;
}
19
Source : ConfigValidator.cs
with Apache License 2.0
from awslabs
with Apache License 2.0
from awslabs
public bool ValidateSchema(string configBaseDirectory, string configFile, IConfigurationRoot config, out IList<string> messages)
{
IDictionary<string, string> sources = new Dictionary<string, string>();
IDictionary<string, string> sinks = new Dictionary<string, string>();
var configFilePath = Path.Combine(configBaseDirectory, configFile);
using (StreamReader configReader = File.OpenText(configFilePath))
using (JsonTextReader jsonReader = new JsonTextReader(configReader))
{
JToken token = JToken.ReadFrom(new JsonTextReader(configReader));
return token.IsValid(_schema, out messages)
&& LoadSources(sources, config, messages)
&& LoadSinks(sinks, config, messages)
&& CheckPipes(sources, sinks, config, messages);
}
}
19
Source : SimpleParameterStore.cs
with Apache License 2.0
from awslabs
with Apache License 2.0
from awslabs
private void LoadParameters()
{
using (var textReader = File.OpenText(_configPath))
{
int lineNumber = 0;
while (!textReader.EndOfStream)
{
lineNumber++;
string line = textReader.ReadLine();
if (!string.IsNullOrWhiteSpace(line))
{
//Split by first '=' so that the value can contain '='
int posEqual = line.IndexOf('=');
if (posEqual < 0)
{
throw new Exception($"Error reading config file {_configPath} line {lineNumber}");
}
else
{
_parameters[line.Substring(0, posEqual)] = line.Substring(posEqual + 1);
}
}
}
}
}
19
Source : GoSiteEnabler.cs
with Apache License 2.0
from Azure-App-Service
with Apache License 2.0
from Azure-App-Service
public static bool LooksLikeGo(string siteFolder)
{
string[] files = Directory.GetFiles(siteFolder, GoFilePattern, SearchOption.TopDirectoryOnly);
foreach (var filePath in files)
{
string line = null;
using (var reader = File.OpenText(filePath))
{
while ((line = reader.ReadLine()) != null)
{
if (line.StartsWith(MainPackage, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
}
}
return false;
}
19
Source : DeploymentHelper.cs
with MIT License
from Azure-Samples
with MIT License
from Azure-Samples
private JObject GetJsonFileContents(string pathToJson)
{
JObject templatefileContent = new JObject();
using (StreamReader file = File.OpenText(pathToJson))
{
using (JsonTextReader reader = new JsonTextReader(file))
{
templatefileContent = (JObject)JToken.ReadFrom(reader);
return templatefileContent;
}
}
}
19
Source : TestBase.cs
with MIT License
from Azure-Samples
with MIT License
from Azure-Samples
private void SetEnvironmentVariables()
{
using (var settingsFile = File.OpenText("launchSettings.json"))
{
JsonTextReader jsonReader = new JsonTextReader(settingsFile);
JObject jsonObject = JObject.Load(jsonReader);
List<JProperty> envVariables = jsonObject
.GetValue("Values")
.OfType<JProperty>()
.ToList();
foreach (JProperty property in envVariables)
{
Environment.SetEnvironmentVariable(property.Name, property.Value.ToString());
}
}
}
19
Source : Options.cs
with The Unlicense
from BattletechModders
with The Unlicense
from BattletechModders
public static IEnumerable<string> GetArgumentsFromFile (string file)
{
return GetArguments (File.OpenText (file), true);
}
19
Source : ControllerManager.cs
with MIT License
from beef331
with MIT License
from beef331
public void LoadCustomScheme(string path)
{
StreamReader reader = File.OpenText(path);
string line;
PressedButton parsedButton;
InputAxis parsedAxis;
while((line = reader.ReadLine()) != null)
{
string[] items = line.Split('=');
if (Enum.IsDefined(typeof(PressedButton), items[0]))
{
parsedButton = (PressedButton)Enum.Parse(typeof(PressedButton), items[0]);
if (!mappedController.ContainsKey(parsedButton))
{
mappedController.Add(parsedButton, (KeyCode)Enum.Parse(typeof(KeyCode), items[1]));
}
else
{
mappedController[parsedButton] = (KeyCode)Enum.Parse(typeof(KeyCode), items[1]);
}
}else if (Enum.IsDefined(typeof(InputAxis), items[0]))
{
parsedAxis = (InputAxis)Enum.Parse(typeof(InputAxis), items[0]);
if (!mappedController.ContainsKey(parsedAxis))
{
mappedController.Add(parsedAxis, items[1]);
}
else
{
mappedController[parsedAxis] = items[1];
}
}
}
}
19
Source : Parser.cs
with MIT License
from bing-framework
with MIT License
from bing-framework
public static ParsedEnreplacedy Parse(string mappingFile)
{
if (string.IsNullOrEmpty(mappingFile) || !File.Exists(mappingFile))
return null;
var parser = new CSharpParser();
CompilationUnit compilationUnit;
using (var stream = File.OpenText(mappingFile))
compilationUnit = parser.Parse(stream, mappingFile);
var visitor = new MappingVisitor();
visitor.VisitCompilationUnit(compilationUnit, null);
var parsedEnreplacedy = visitor.ParsedEnreplacedy;
if (parsedEnreplacedy != null)
Debug.WriteLine("Parsed Mapping File: '{0}'; Properties: {1}; Relationships: {2}",
Path.GetFileName(mappingFile),
parsedEnreplacedy.Properties.Count,
parsedEnreplacedy.Relationships.Count);
return parsedEnreplacedy;
}
19
Source : Parser.cs
with MIT License
from bing-framework
with MIT License
from bing-framework
public static ParsedContext Parse(string contextFile)
{
if (string.IsNullOrEmpty(contextFile) || !File.Exists(contextFile))
return null;
var parser = new CSharpParser();
CompilationUnit compilationUnit;
using (var stream = File.OpenText(contextFile))
compilationUnit = parser.Parse(stream, contextFile);
var visitor = new ContextVisitor();
visitor.VisitCompilationUnit(compilationUnit, null);
var parsedContext = visitor.ParsedContext;
if (parsedContext != null)
Debug.WriteLine("Parsed Context File: '{0}'; Enreplacedies: {1}",
Path.GetFileName(contextFile),
parsedContext.Properties.Count);
return parsedContext;
}
19
Source : SecretKeyStoreService.cs
with MIT License
from bmresearch
with MIT License
from bmresearch
public byte[] DecryptKeyStoreFromFile(string preplacedword, string filePath)
{
if (preplacedword == null) throw new ArgumentNullException(nameof(preplacedword));
if (filePath == null) throw new ArgumentNullException(nameof(filePath));
using var file = File.OpenText(filePath);
var json = file.ReadToEnd();
return DecryptKeyStoreFromJson(preplacedword, json);
}
19
Source : GameRecord.cs
with MIT License
from boonwin
with MIT License
from boonwin
public static List<GameRecord> LoadGameRecordFromFile(string gameHistoryFile)
{
List<GameRecord> gameRecords = new List<GameRecord>();
if (File.Exists(gameHistoryFile))
{
using (StreamReader streamReader = File.OpenText(gameHistoryFile))
{
string dataLine;
while ((dataLine = streamReader.ReadLine()) != null)
{
var singleGameRecord = new GameRecord();
singleGameRecord = JsonConvert.DeserializeObject<GameRecord>(dataLine);
gameRecords.Add(singleGameRecord);
}
}
}
return gameRecords;
}
See More Examples