Here are the examples of the csharp api System.IO.StreamReader.Close() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1383 Examples
19
Source : Form1.cs
with MIT License
from Arefu
with MIT License
from Arefu
private void OpenToolStripMenuItem_Click(object Sender, EventArgs Args)
{
if (FileQuickViewList.Nodes.Count != 0) return;
Reader?.Close();
try
{
InstallDir = Utilities.GetInstallDir();
Reader = new StreamReader(File.Open($"{InstallDir}\\YGO_DATA.TOC", FileMode.Open, FileAccess.Read));
}
catch
{
var Reply = MessageBox.Show(this, "Do You Want To Locate Game?", "Game Not Fuond!",
MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk);
if (Reply == DialogResult.No) Environment.Exit(1);
else
using (var Ofd = new OpenFileDialog())
{
Ofd.replacedle = "Select YuGiOh.exe";
Ofd.Filter = "YuGiOh.exe | YuGiOh.exe";
var Result = Ofd.ShowDialog();
if (Result != DialogResult.OK) Environment.Exit(1);
Reader = new StreamReader(File.Open($"{new FileInfo(Ofd.FileName).DirectoryName}\\YGO_DATA.TOC",
FileMode.Open, FileAccess.Read));
InstallDir = new FileInfo(Ofd.FileName).DirectoryName;
}
}
Reader.ReadLine();
GameLocLabel.ForeColor = Color.Green;
GameLocLabel.Text = "Game Loaded";
var RootNode = new TreeNode("YGO_DATA");
FileQuickViewList.Nodes.Add(RootNode);
while (!Reader.EndOfStream)
{
var Line = Reader.ReadLine();
if (Line == null) continue;
Line = Line.TrimStart(' ');
Line = Regex.Replace(Line, @" +", " ", RegexOptions.Compiled);
var LineData = Line.Split(' ');
Data.Add(new FileData(Utilities.HexToDec(LineData[0]), Utilities.HexToDec(LineData[1]), LineData[2]));
LineData[2].Split('\\').Aggregate(RootNode,
(Current, File) => Current.Nodes.ContainsKey(File)
? Current.Nodes[File]
: Current.Nodes.Add(File, File));
}
Reader?.Close();
GiveIcons(FileQuickViewList.Nodes[0]);
FileQuickViewList.Nodes[0].Expand();
FileQuickViewList.SelectedNode = FileQuickViewList.Nodes[0];
FileQuickViewList_NodeMouseClick(new object(),
new TreeNodeMouseClickEventArgs(FileQuickViewList.Nodes[0], MouseButtons.Left, 1, 0, 0));
}
19
Source : Form1.cs
with MIT License
from Arefu
with MIT License
from Arefu
private void CloseToolStripMenuItem_Click(object Sender, EventArgs Args)
{
MainFileView.Items.Clear();
FileQuickViewList.Nodes.Clear();
Reader?.Close();
GameLocLabel.ForeColor = Color.Red;
GameLocLabel.Text = "Game Not Loaded";
}
19
Source : Form1.cs
with MIT License
from Arefu
with MIT License
from Arefu
private void installToolStripMenuItem_Click(object sender, EventArgs e)
{
using (var OFD = new OpenFileDialog())
{
OFD.replacedle = "Select Mod To Enable";
OFD.Filter = "Wolf Mod Data |*.moddta";
if (OFD.ShowDialog() != DialogResult.OK) return;
if (!File.Exists(OFD.FileName.Replace("moddta", "modpkg")))
throw new Exception("Mod Package Not Found! Please Read The Wiki On How To Create Mods.");
var ModFileInfo = new JavaScriptSerializer().Deserialize<ModInfo>(File.ReadAllText(OFD.FileName));
var AllFilesFound = true;
var CompareSizes = new Dictionary<long, ModFile>();
Reader?.Close();
using (var GetFileSizeReader = new StreamReader(File.Open($"{Utilities.GetInstallDir()}\\YGO_DATA.TOC", FileMode.Open, FileAccess.Read)))
{
for (var Count = 0; Count < ModFileInfo.Files.Count; Count++)
{
GetFileSizeReader.BaseStream.Position = 0;
GetFileSizeReader.ReadLine();
while (!GetFileSizeReader.EndOfStream)
{
var Line = GetFileSizeReader.ReadLine();
if (Line == null) break;
Line = Line.TrimStart(' ');
Line = Regex.Replace(Line, @" +", " ", RegexOptions.Compiled);
var LineData = Line.Split(' ');
if (new FileInfo(LineData[2]).Name == new FileInfo(ModFileInfo.Files[Count]).Name)
{
GetFileSizeReader.BaseStream.Position = 0; //Because We're Breaking We Need To Reset Stream DUH
GetFileSizeReader.ReadLine();
AllFilesFound = true;
CompareSizes.Add(Utilities.HexToDec(LineData[0]), new ModFile(ModFileInfo, Count));
break;
}
AllFilesFound = false;
}
}
}
if (AllFilesFound == false)
{
var Reply = MessageBox.Show("Not All Files Were Found In The TOC File, Do You Want To Contiue?", "Lost Files Found In Mod!", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
if (Reply == DialogResult.No) return;
}
using (var LogWriter = File.AppendText("Install_Log.log"))
{
foreach (var ModFile in CompareSizes)
if (ModFile.Key < ModFile.Value.FileSize)
{
var Reply = MessageBox.Show("File Already In Game Is Bigger, Do You Want To Continue?", "File Size Mismatch!", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
if (Reply == DialogResult.No)
{
LogWriter.Write($"[{DateTime.Now}]: Didn't Inject {ModFile.Value.FileName}, Discarded By User!\n\r");
continue;
}
LogWriter.Write($"[{DateTime.Now}]: Injecting {ModFile.Value.FileName} With Size Of {ModFile.Value.FileSize} The original file is bigger\n\r");
//Open DAT, Insert In Right Place...
}
else
{
LogWriter.Write($"[{DateTime.Now}]: Injecting {ModFile.Value.FileName} With Size Of {ModFile.Value.FileSize} This File Is Smaller!\n\r");
var Sum = 0L;
var NullOutSize = 0L;
Reader?.Close();
using (Reader = new StreamReader(File.Open($"{InstallDir}\\YGO_DATA.TOC", FileMode.Open, FileAccess.Read)))
{
Reader.BaseStream.Position = 0;
Reader.ReadLine();
while (!Reader.EndOfStream
) //Breaks on 116a658 44 D3D11\characters\m9575_number_39_utopia\m9575_number_39_utopia.phyre ?
{
var Line = Reader.ReadLine();
if (Line == null) break;
Line = Line.TrimStart(' ');
Line = Regex.Replace(Line, @" +", " ", RegexOptions.Compiled);
var LineData = Line.Split(' ');
if (LineData[2] == ModFile.Value.FileName)
{
NullOutSize = Utilities.HexToDec(LineData[0]);
break;
}
Sum = Sum + Utilities.HexToDec(LineData[0]);
}
Debug.WriteLine(Sum);
using (var Writer = new BinaryWriter(File.Open($"{InstallDir}\\YGO_DATA.DAT", FileMode.Open, FileAccess.ReadWrite)))
{
Writer.BaseStream.Position = Sum;
var NullCount = 0L;
do
{
Writer.Write(0x00);
NullCount++;
} while (NullCount < NullOutSize);
}
}
}
}
}
}
19
Source : MinerProgramBase.cs
with GNU General Public License v3.0
from arunsatyarth
with GNU General Public License v3.0
from arunsatyarth
public virtual void LoadScript()
{
try
{
if (AutomaticScriptGeneration)
{
GenerateScript();
}
else
{
FileStream stream = File.Open(BATFILE, FileMode.Open);
StreamReader sr = new StreamReader(stream);
Script = sr.ReadToEnd();
sr.Close();
}
}
catch (Exception e)
{
}
}
19
Source : Program.cs
with GNU General Public License v3.0
from arunsatyarth
with GNU General Public License v3.0
from arunsatyarth
[STAThread]
static void Main()
{
try
{
string filename = @"c:\pics\a.txt";
Stream stream = new FileStream(filename, FileMode.Open);
StreamReader sr = new StreamReader(stream);
string s = sr.ReadToEnd();
sr.Close();
filename = @"c:\pics\b.txt";
Stream stream2 = new FileStream(filename, FileMode.Open);
StreamReader sr2 = new StreamReader(stream2);
string s2 = sr2.ReadToEnd();
sr2.Close();
filename = @"c:\pics\c.txt";
Stream stream3 = new FileStream(filename, FileMode.Open);
StreamReader sr3 = new StreamReader(stream3);
string s3 = sr3.ReadToEnd();
sr3.Close();
MinerDataResult minerResult = (MinerDataResult)new JavaScriptSerializer().Deserialize(s, typeof(MinerDataResult));
if (minerResult.Parse(new OneMiner.Coins.Equihash.ClaymoreMinerZcash.ClayMoreZcashReader.ZcashClaymoreResultParser(s2, true)))
{
}
OneMiner.Coins.Equihash.EWBFMiner.EWBFData r = (OneMiner.Coins.Equihash.EWBFMiner.EWBFData)new JavaScriptSerializer()
.Deserialize(s3, typeof(OneMiner.Coins.Equihash.EWBFMiner.EWBFData));
OneMiner.Coins.Equihash.EWBFMiner.EWBFData ewbfData = r;
if (ewbfData.Parse(new OneMiner.Coins.Equihash.EWBFMiner.EWBFReader.EWBFReaderResultParser("", true)))
{
}
//Bring only a single instance
bool onlyInstance = false;
mutex = new Mutex(true, "UniqueApplicationName", out onlyInstance);
if (!onlyInstance)
{
IntPtr handle = WinApi.FindWindow(null, "OneMiner - 1 Click Miner for Ethereum, ZCash");
if (handle != IntPtr.Zero)
WinApi.PostMessage(handle, 3000, IntPtr.Zero, IntPtr.Zero);
return;
}
}
catch (Exception e)
{
}
IView view = Factory.Instance.ViewObject;
view.InitializeView();
Factory.Instance.CoreObject.LoadDBData();
view.StartView();
}
19
Source : ConfigFileManager.cs
with GNU General Public License v3.0
from arunsatyarth
with GNU General Public License v3.0
from arunsatyarth
private void LoadData()
{
try
{
string filename = GetFileName();
Stream stream = new FileStream(filename, FileMode.Open);
StreamReader sr = new StreamReader(stream);
Data = sr.ReadToEnd();
sr.Close();
}
catch (Exception e)
{
}
}
19
Source : ObjLoader.cs
with GNU General Public License v2.0
from Asixa
with GNU General Public License v2.0
from Asixa
public static ObjMesh load(string path)
{
if (!File.Exists(path))
throw new FileNotFoundException();
if (!path.EndsWith(".obj"))
throw new FileNotFoundException();
var reader = new StreamReader(path, Encoding.Default);
var content = reader.ReadToEnd();
reader.Close();
return new ObjMesh().LoadFromObj(content); ;
}
19
Source : ScriptGenerator.cs
with MIT License
from Asixa
with MIT License
from Asixa
public string Generate(int Appid, String game_path,String Description)
{
string path = Directory.GetCurrentDirectory();
string filePath = path + @"\Tools\Steamcmd\Scripts\app_build_" + Appid + ".vpf";
app_build_script_path = filePath;
if (File.Exists(filePath))
{
File.Delete(filePath);
}
read_filestream = new FileStream(path + @"\Tools\Steamcmd\Scripts\Template\app_build_[].vpf", FileMode.Open);
write_filestream = new FileStream(filePath, FileMode.CreateNew);
stream_writer = new StreamWriter(write_filestream);
stream_reader = new StreamReader(read_filestream);
string app_build_script = stream_reader.ReadToEnd();
app_build_script = app_build_script.Replace("[Appid]", Appid.ToString());
app_build_script = app_build_script.Replace("[Appid1]", (Appid + 1).ToString());
app_build_script = app_build_script.Replace("[Description]", Description);
stream_writer.WriteLine(app_build_script);
stream_writer.Close();
stream_reader.Close();
write_filestream.Close();
read_filestream.Close();
filePath = path + @"\Tools\Steamcmd\Scripts\depot_build_" + (Appid+1) + ".vdf";
if (File.Exists(filePath))
{
File.Delete(filePath);
}
read_filestream = new FileStream(path + @"\Tools\Steamcmd\Scripts\Template\depot_build_[].vdf", FileMode.Open);
write_filestream = new FileStream(filePath, FileMode.CreateNew);
stream_writer = new StreamWriter(write_filestream);
stream_reader = new StreamReader(read_filestream);
string depot_build_script = stream_reader.ReadToEnd();
depot_build_script = depot_build_script.Replace("[Appid]", (Appid+1).ToString());
depot_build_script = depot_build_script.Replace("[P_Game_path]", Directory.GetParent(game_path).FullName+@"\");
depot_build_script = depot_build_script.Replace("[Game_path]", ".\\"+game_path + @"\*");
stream_writer.WriteLine(depot_build_script);
stream_writer.Close();
stream_reader.Close();
write_filestream.Close();
read_filestream.Close();
CompleteEvent.Invoke();
return app_build_script_path;
}
19
Source : WebPageToPDF.cs
with MIT License
from aspose-pdf
with MIT License
from aspose-pdf
public static void Run()
{
try
{
// ExStart:WebPageToPDF
// The path to the doreplacedents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_DoreplacedentConversion();
// Create a request for the URL.
WebRequest request = WebRequest.Create("https:// En.wikipedia.org/wiki/Main_Page");
// If required by the server, set the credentials.
request.Credentials = CredentialCache.DefaultCredentials;
// Time out in miliseconds before the request times out
// Request.Timeout = 100;
// Get the response.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
MemoryStream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(responseFromServer));
HtmlLoadOptions options = new HtmlLoadOptions("https:// En.wikipedia.org/wiki/");
// Load HTML file
Doreplacedent pdfDoreplacedent = new Doreplacedent(stream, options);
options.PageInfo.IsLandscape = true;
// Save output as PDF format
pdfDoreplacedent.Save(dataDir + "WebPageToPDF_out.pdf");
// ExEnd:WebPageToPDF
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
19
Source : ProvideCredentialsDuringHTMLToPDF.cs
with MIT License
from aspose-pdf
with MIT License
from aspose-pdf
public static void Run()
{
try
{
// ExStart:ProvideCredentialsDuringHTMLToPDF
// The path to the doreplacedents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_DoreplacedentConversion();
// Create a request for the URL.
WebRequest request = WebRequest.Create("http:// My.signchart.com/Report/PrintBook.asp?ProjectGuid=6FB9DBB0-");
// If required by the server, set the credentials.
request.Credentials = CredentialCache.DefaultCredentials;
// Get the response.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
MemoryStream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(responseFromServer));
HtmlLoadOptions options = new HtmlLoadOptions("http:// My.signchart.com/");
options.ExternalResourcesCredentials = CredentialCache.DefaultCredentials;
// Load HTML file
Doreplacedent pdfDoreplacedent = new Doreplacedent(stream, options);
// Save resultant file
pdfDoreplacedent.Save("ProvideCredentialsDuringHTMLToPDF_out.pdf");
// ExEnd:ProvideCredentialsDuringHTMLToPDF
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
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 : Compiler.cs
with GNU General Public License v3.0
from AtomCrafty
with GNU General Public License v3.0
from AtomCrafty
public YukaScript FromSource(string scriptPath, string stringPath) {
scriptname = Path.GetFileNameWithoutExtension(scriptPath);
#region Import meta information
if(File.Exists(stringPath)) {
#region Parse CSV
StreamReader sr;
int offset = -1;
bool quoted = false;
bool justLeftQuote = false;
List<List<string>> rows = new List<List<string>>();
List<string> row = new List<string>();
StringBuilder cell = new StringBuilder();
sr = new StreamReader(new FileStream(stringPath, FileMode.Open));
while(!sr.EndOfStream) {
offset++;
char ch = (char)sr.Read();
switch(ch) {
case '"': {
if(quoted) {
quoted = false;
justLeftQuote = true;
continue;
}
else if(justLeftQuote) {
quoted = true;
cell.Append('"');
}
else {
quoted = true;
}
break;
}
case ',': {
if(quoted) {
cell.Append(',');
}
else {
row.Add(cell.ToString());
cell.Clear();
}
break;
}
case '\r': {
// do nothing
break;
}
case '\n': {
if(quoted) {
cell.Append('\n');
}
else {
row.Add(cell.ToString());
rows.Add(row);
row = new List<string>();
cell.Clear();
}
break;
}
default: {
cell.Append(ch);
break;
}
}
justLeftQuote = false;
}
sr.Close();
row.Add(cell.ToString());
rows.Add(row);
#endregion
#region Populate string table
//int metaColumnID = 7;
int maxTextColumn = 6;
int minTextColumn = 2;
int defaultLineWidth = TextUtils.defaultLineWidth;
int defaultCharWidth = TextUtils.defaultCharWidth;
bool removeQuotes = true;
bool correctPunctuation = true;
bool replaceSpecialChars = true;
bool wrapWords = true;
foreach(List<string> entry in rows) {
if(entry.Count < 3) continue;
#region Handle row
#region Read meta data
int currentLineWidth = defaultLineWidth;
int currentCharWidth = defaultCharWidth;
string[] metaData = entry[1].Split('\n');
string speaker = "";
foreach(string meta in metaData) {
string[] data = meta.Split(new[] { ':' }, 2);
if(data.Length == 2) {
switch(data[0].Trim().ToLower()) {
case "lw":
case "linewidth":
currentLineWidth = int.Parse(data[1].Trim());
break;
case "dlw":
case "defaultlinewidth":
defaultLineWidth = int.Parse(data[1].Trim());
currentLineWidth = defaultLineWidth;
break;
case "cw":
case "charwidth":
currentCharWidth = int.Parse(data[1].Trim());
break;
case "dcw":
case "defaultcharwidth":
defaultCharWidth = int.Parse(data[1].Trim());
currentCharWidth = defaultCharWidth;
break;
case "rmq":
case "rmquotes":
case "removequotes":
removeQuotes = bool.Parse(data[1].Trim());
break;
case "cp":
case "correctpunctiation":
correctPunctuation = bool.Parse(data[1].Trim());
break;
case "rsc":
case "replacespecialchars":
replaceSpecialChars = bool.Parse(data[1].Trim());
break;
case "ww":
case "wordwrap":
wrapWords = bool.Parse(data[1].Trim());
break;
}
}
else if(entry[0].Length > 0 && "LNS".Contains(entry[0][0].ToString())) {
speaker = meta;
}
}
#endregion
#region Format string
if(entry[0].Length > 0 && "LNS".Contains(entry[0][0].ToString())) {
/*if(entry.Count > metaColumnID && entry[metaColumnID].Trim().Length > 0) {
Console.WriteLine(entry[0] + ": " + entry[metaColumnID].Trim('\n'));
// stringTable[entry[0]] = entry[metaColumnID].Trim('\n');
// continue;
}*/
for(int i = maxTextColumn; i >= minTextColumn; i--) {
if(i < entry.Count && !entry[i].Equals("") && !entry[i].Equals(".")) {
string value = entry[i];
if(entry[0][0] == 'L') {
value = value.Trim('\n', '%', '#', '「', '」');
if(value.Length > 1 && value[0] == '"' && value[value.Length - 1] == '"' && removeQuotes) {
value = value.Substring(1, value.Length - 2);
}
if(replaceSpecialChars) {
// get rid of most replacedanese double width punctuation characters
value = TextUtils.ReplaceSpecialChars(value);
}
if(correctPunctuation) {
value = TextUtils.CorrectPunctuation(value);
}
value = TextUtils.EncodeYukaString(value);
/*
var lines = TextUtils.WrapWords(value, currentLineWidth, new TextUtils.FontMetrics(currentCharWidth));
value = string.Join("", lines).Trim();
Console.WriteLine();
Console.WriteLine($" line width: {currentLineWidth}px");
Console.WriteLine($" char width: {currentCharWidth}px / {currentCharWidth / 2}px");
Console.WriteLine(" speaker: " + (speaker.Length > 0 ? speaker : "none"));
Console.WriteLine(new string('-', currentLineWidth / currentCharWidth * 2));
Console.BackgroundColor = ConsoleColor.DarkBlue;
Console.ForegroundColor = ConsoleColor.Magenta;
foreach(var line in lines) {
Console.WriteLine(line);
}
Console.ResetColor();
//*/
if(wrapWords) {
value = string.Join(
"@m(1000)",
value.Split('\n').Select(
line => string.Join(
" ",
line.Split(' ').Select(
word => $"@m({word.Length + 1}){word}"
)
)
)
);
}
}
//Console.WriteLine(entry[0] + ": " + value);
stringTable[entry[0]] = new ScriptLine(currentCharWidth, speaker, value);
break;
}
}
}
#endregion
#endregion
}
#endregion
}
#endregion
#region Parse script file
BinaryReader br = new BinaryReader(new FileStream(scriptPath, FileMode.Open));
List<ScriptElement> commands = new List<ScriptElement>();
SkipWhitespace(br);
ScriptElement elem;
while((elem = NextScriptElement(br)) != null) {
if(!(elem is DummyScriptElement)) {
commands.Add(elem);
if(FlagCollection.current.Has('v')) {
Console.WriteLine(elem);
}
}
}
br.Close();
#endregion
return new YukaScript(commands, stringTable);
}
19
Source : StandardMesh.cs
with MIT License
from austinvaness
with MIT License
from austinvaness
public static StandardMesh ParseStl(string fileName)
{
List<Triangle> triangles = new List<Triangle>();
HashSet<Line> edges = new HashSet<Line>();
HashSet<Vector3> verticies = new HashSet<Vector3>();
Vector3 max = new Vector3(float.MinValue, float.MinValue, float.MinValue);
Vector3 min = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue);
BinaryReader br = new BinaryReader(File.OpenRead(fileName));
ASCIIEncoding ascii = new ASCIIEncoding();
string header = ascii.GetString(br.ReadBytes(80));
int errors = 0;
int total = 0;
if (header.StartsWith("solid"))
{
br.Close();
StreamReader sr = new StreamReader(File.OpenRead(fileName), ascii);
while (Triangle.ReadFindAscii(sr, out string triangleLine))
{
if (Triangle.ReadAscii(sr, triangleLine, out Triangle t))
{
min = Vector3.Min(min, t.aabb.min);
max = Vector3.Max(max, t.aabb.max);
triangles.Add(t);
edges.Add(t.edge12);
edges.Add(t.edge31);
edges.Add(t.edge23);
verticies.Add(t.vertex1);
verticies.Add(t.vertex2);
verticies.Add(t.vertex3);
}
else
{
errors++;
}
total++;
}
sr.Close();
}
else
{
uint count = br.ReadUInt32();
total = (int)count;
for (uint i = 0; i < count; i++)
{
if(Triangle.ReadBinary(br, out Triangle t))
{
min = Vector3.Min(min, t.aabb.min);
max = Vector3.Max(max, t.aabb.max);
triangles.Add(t);
edges.Add(t.edge12);
edges.Add(t.edge31);
edges.Add(t.edge23);
verticies.Add(t.vertex1);
verticies.Add(t.vertex2);
verticies.Add(t.vertex3);
}
else
{
errors++;
}
}
br.Close();
}
if (errors / (float)total > GlobalConstants.meshErrorThreshold)
MessageBox.Show(errors + " invalid triangles were ignored in the stl file.");
return new StandardMesh(triangles, edges, verticies, min, max);
}
19
Source : Polyline.cs
with MIT License
from Autodesk
with MIT License
from Autodesk
public static List<Polyline> ReadFromDUCTPictureFile(File file)
{
List<Polyline> polylines = new List<Polyline>();
string CurCult = System.Threading.Thread.CurrentThread.CurrentUICulture.Name;
try
{
System.Threading.Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-GB");
string strBuff = "";
using (
System.IO.FileStream FS = new System.IO.FileStream(file.Path,
System.IO.FileMode.Open,
System.IO.FileAccess.Read))
{
using (System.IO.StreamReader SR = new System.IO.StreamReader(FS))
{
strBuff = SR.ReadToEnd();
SR.Close();
}
FS.Close();
}
strBuff = strBuff.Replace(Strings.Chr(9).ToString(), "");
strBuff = strBuff.Replace(Strings.Chr(13).ToString(), "");
string[] strSpl = strBuff.Split(Strings.Chr(10));
List<List<int>> instructions = new List<List<int>>();
List<Point> points = new List<Point>();
// Check to see if the file is in inches or mm
bool isInInches = strSpl[1].Trim().ToLower().EndsWith("inches");
// Ignore the header lines just concentrate on the juicy bits
for (int lineIndex = 5; lineIndex <= strSpl.Length - 1; lineIndex++)
{
// Collect up all the numeric values on the line
List<double> elementsOnLine = new List<double>();
foreach (string stringElement in strSpl[lineIndex].Split(' '))
{
double value = 0;
if (double.TryParse(stringElement,
NumberStyles.Any,
CultureInfo.InvariantCulture,
out value))
{
elementsOnLine.Add(value);
}
}
if (elementsOnLine.Count == 2)
{
// If there are two values then it is an instruction line
instructions.Add(new List<int>
{
Convert.ToInt32(elementsOnLine[0]),
Convert.ToInt32(elementsOnLine[1])
});
}
else if (elementsOnLine.Count >= 3)
{
// Otherwise it is a point data line
if (isInInches)
{
points.Add(new Point(elementsOnLine[0] * 25.4, elementsOnLine[1] * 25.4, elementsOnLine[2] * 25.4));
}
else
{
points.Add(new Point(elementsOnLine[0], elementsOnLine[1], elementsOnLine[2]));
}
}
}
// So we have all the data, now we need to populate the polyline and spline lists
// This keeps track of which point we are looking at for the current instruction
int pointIndex = 0;
for (int instructionIndex = 0; instructionIndex <= instructions.Count - 1; instructionIndex++)
{
if ((instructions[instructionIndex][0] & 1024) == 1024)
{
// Bezier curves
Spline spline = new Spline();
int pixelIndex = 1;
if ((instructions[instructionIndex][0] & 24) == 24)
{
pixelIndex = -1;
}
while (pixelIndex < instructions[instructionIndex][1])
if (pixelIndex == -1)
{
// First pixel only has tangency out
Vector directionOut = points[pointIndex + pixelIndex + 1] - points[pointIndex + pixelIndex];
double distanceOut = directionOut.Magnitude;
directionOut.Normalize();
spline.Add(new SplinePoint(points[pointIndex + pixelIndex],
directionOut,
distanceOut,
directionOut,
distanceOut));
pixelIndex += 3;
}
else if (instructions[instructionIndex][1] - pixelIndex == 1)
{
// Last pixel only has tangency in
Vector directionIn = points[pointIndex + pixelIndex] - points[pointIndex + pixelIndex - 1];
double distanceIn = directionIn.Magnitude;
directionIn.Normalize();
spline.Add(new SplinePoint(points[pointIndex + pixelIndex],
directionIn,
distanceIn,
directionIn,
distanceIn));
pixelIndex += 3;
}
else
{
// Pixel has tangency in and out
Vector directionIn = points[pointIndex + pixelIndex] - points[pointIndex + pixelIndex - 1];
double distanceIn = directionIn.Magnitude;
directionIn.Normalize();
Vector directionOut = points[pointIndex + pixelIndex + 1] - points[pointIndex + pixelIndex];
double distanceOut = directionOut.Magnitude;
directionOut.Normalize();
spline.Add(new SplinePoint(points[pointIndex + pixelIndex],
directionIn,
distanceIn,
directionOut,
distanceOut));
pixelIndex += 3;
}
if ((instructions[instructionIndex][0] & 24) == 0)
{
// Starting a new section
Polyline polyline = new Polyline(spline, 0.01);
polylines.Add(polyline);
}
else
{
// Continuing the last section
Polyline polyline = new Polyline(spline, 0.01);
// Add all points apart from the first one
for (int i = 1; i <= polyline.Count - 1; i++)
{
polylines[polylines.Count - 1].Add(polyline[i]);
}
}
pointIndex += instructions[instructionIndex][1];
}
else if ((instructions[instructionIndex][0] & 512) == 512)
{
// Conic arcs
Spline intermediateCurve = new Spline();
Spline spline = new Spline();
int pixelIndex = 0;
if ((instructions[instructionIndex][0] & 24) == 24)
{
pixelIndex = -1;
}
while (pixelIndex < instructions[instructionIndex][1])
{
intermediateCurve.Add(new SplinePoint(points[pointIndex + pixelIndex]));
// If there are three points on the curve
if (intermediateCurve.Count == 3)
{
intermediateCurve.FreeTangentsAndMagnitudes();
if (spline.Count != 0)
{
// If the spline curve already has points then dont add the first one, just set the output tangent and magnitude
spline.Last().MagnitudeAfter = intermediateCurve[0].MagnitudeAfter;
spline.Last().DirectionAfter = intermediateCurve[0].DirectionAfter;
}
else
{
// else add first point
spline.Add(intermediateCurve[0]);
}
// add second and third point
spline.Add(intermediateCurve[1]);
spline.Add(intermediateCurve[2]);
var p = intermediateCurve[2];
// reset intermediate curve and add last point
intermediateCurve.Clear();
intermediateCurve.Add(p.Clone());
}
pixelIndex += 1;
}
if ((instructions[instructionIndex][0] & 24) == 0)
{
// Starting a new section
Polyline polyline = new Polyline(spline, 0.01);
polylines.Add(polyline);
}
else
{
// Continuing the last section
Polyline polyline = new Polyline(spline, 0.01);
// Add all points apart from the first one
for (int i = 1; i <= polyline.Count - 1; i++)
{
polylines[polylines.Count - 1].Add(polyline[i]);
}
}
pointIndex += instructions[instructionIndex][1];
}
else
{
// Polylines
if ((instructions[instructionIndex][0] & 24) == 0)
{
// Starting a new section
Polyline polyline =
new Polyline(
new List<Point>(points.GetRange(pointIndex, instructions[instructionIndex][1]).ToArray()));
polylines.Add(polyline);
}
else
{
// Continuing the last section
polylines[polylines.Count - 1].AddRange(
points.GetRange(pointIndex, instructions[instructionIndex][1]).ToArray());
}
pointIndex += instructions[instructionIndex][1];
}
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
System.Threading.Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(CurCult);
}
return polylines;
}
19
Source : Workplane.cs
with MIT License
from Autodesk
with MIT License
from Autodesk
private Tuple<double[,], double[]> GetRotationMatrixAndTranslationFromMatFile(File matFile)
{
StreamReader myFile = new StreamReader(matFile.Path);
double xRotation = 0;
double yRotation = 0;
double zRotation = 0;
var translation = new double[3];
bool invert = false;
double rotationInDegrees;
while (myFile.EndOfStream == false)
{
string myLine = myFile.ReadLine();
string[] splitLine = myLine.Split();
var lineValues = splitLine.Where(x => !string.IsNullOrEmpty(x)).ToList();
// PowerInspect writes the MAT files using InvariantCulture
if (lineValues.Any())
{
switch (lineValues[0])
{
case "R":
switch (lineValues[1])
{
case "X":
rotationInDegrees = Convert.ToDouble(lineValues[2], CultureInfo.InvariantCulture);
xRotation = rotationInDegrees * Math.PI / 180;
break;
case "Y":
rotationInDegrees = Convert.ToDouble(lineValues[2], CultureInfo.InvariantCulture);
yRotation = rotationInDegrees * Math.PI / 180;
break;
case "Z":
rotationInDegrees = Convert.ToDouble(lineValues[2], CultureInfo.InvariantCulture);
zRotation = rotationInDegrees * Math.PI / 180;
break;
}
break;
case "T":
translation[0] = Convert.ToDouble(lineValues[1], CultureInfo.InvariantCulture);
translation[1] = Convert.ToDouble(lineValues[2], CultureInfo.InvariantCulture);
translation[2] = Convert.ToDouble(lineValues[3], CultureInfo.InvariantCulture);
break;
case "I":
invert = true;
break;
}
}
}
myFile.Close();
// PowerInspect uses the convention XYZ extrinsic (which means 1st rotate around x, then y, then z regarding to the world)
double[,] rotationMatrix = new Angles(xRotation, yRotation, zRotation, Conventions.XYZ).Matrix;
if (invert)
{
//Invert the Rotation matrix and invert the Translation vector.
//This is equivalent to transpose the Rotation Matrix(Rt) and for the translation vector is equivalent to multiply it by -Rt
//(http://www.cg.info.hiroshima-cu.ac.jp/~miyazaki/knowledge/teche53.html)
rotationMatrix = rotationMatrix.Transpose();
var negativeRotationMatrix = rotationMatrix.Multiply(-1);
translation = negativeRotationMatrix.Multiply(translation);
translation[0] = translation[0];
translation[1] = translation[1];
translation[2] = translation[2];
}
return new Tuple<double[,], double[]>(rotationMatrix, translation);
}
19
Source : PathRoot.cs
with Apache License 2.0
from autowarefoundation
with Apache License 2.0
from autowarefoundation
private void OnEnable()
{
PathStartPoint = new List<Vector4> { };
if (isSet)
{
for (int i = 0; i < transform.childCount; i++)
{
PathStartPoint.Add(transform.GetChild(i).GetComponent<PathInfo>().FirstPoint);
}
}
else
{
pathPrefab = Resources.Load("Roads/Path") as GameObject;
root = new DirectoryInfo(path);
files = root.GetFiles();
foreach (var file in files)
{
if (file.Name.EndsWith(".txt"))
{
var infoList = new List<Vector4>();
string name = file.Name.Replace(".txt", "");
sr = new StreamReader(file.FullName);
string line;
while ((line = sr.ReadLine()) != null)
{
string[] strInfo = line.Split(',');
if (strInfo.Length == 4)
{
float.TryParse(strInfo[0], out info.x);
float.TryParse(strInfo[1], out info.y);
float.TryParse(strInfo[2], out info.z);
float.TryParse(strInfo[3], out info.w);
infoList.Add(info);
}
else
{
}
}
sr.Close();
AddPath(infoList, name);
}
}
}
}
19
Source : RTSClient.cs
with Apache License 2.0
from aws-samples
with Apache License 2.0
from aws-samples
private void ConnectToLocalServer()
{
var ipAddrPath = Application.dataPath + "/serverip.txt";
var ipAddrReader = new StreamReader(ipAddrPath);
var ipAddr = ipAddrReader.ReadToEnd();
ipAddrReader.Close();
// typically you'd use the player ID from an authentication system like GameLift,
// however for our demo purposes, just pick a random unique ID
StartCoroutine(ConnectToServer(ipAddr, DEFAULT_TCP_PORT, Guid.NewGuid().ToString()));
}
19
Source : GLSLESProgramWriter.cs
with GNU Lesser General Public License v2.1
from axiom3d
with GNU Lesser General Public License v2.1
from axiom3d
private void CacheDependencyFunctions(string libName)
{
if (this.cachedFunctionLibraries.ContainsKey(libName))
{
return; //lib is already in cach
}
string libFileName = libName + ".glsles";
var dataStream = ResourceGroupManager.Instance.OpenResource(libFileName);
var reader = new StreamReader(dataStream, Encoding.Default);
var functionCache = new Dictionary<string, string>();
string line;
while (!reader.EndOfStream)
{
line = reader.ReadLine();
//Ignore empty lines and comments
if (line.Length > 0)
{
line = line.Trim();
if (line[0] == '/' && line[1] == '*')
{
bool endFound = false;
while (!endFound)
{
//Get the next line
line = reader.ReadLine();
//Skip empties
if (line.Length > 0)
{
//Look for the ending sequence
if (line.Contains("*/"))
{
endFound = true;
}
}
}
}
else if (line.Length > 1 && line[0] != '/' && line[1] != '/')
{
//Break up the line.
string[] tokens = line.Split(' ', '(', '\n', '\r');
//Cache #defines
if (tokens[0] == "#define")
{
this.definesMap.Add(line, libName);
continue;
}
// Try to identify a function definition
// First, look for a return type
if (IsBasicType(tokens[0]) && ((tokens.Length < 3) || tokens[2] != "="))
{
string functionSig = string.Empty;
string functionBody = string.Empty;
FunctionInvocation functionInvoc = null;
//Return type
functionSig = tokens[0];
functionSig += " ";
//Function name
functionSig += tokens[1];
functionSig += "(";
bool foundEndOfSignature = false;
//Now look for all the paraemters, the may span multiple lines
while (!foundEndOfSignature)
{
//Trim whitespace from both sides of the line
line = line.Trim();
//First we want to get everything right of the paren
string[] paramTokens;
if (line.Contains('('))
{
string[] lineTokens = line.Split(')');
paramTokens = lineTokens[1].Split(',');
}
else
{
paramTokens = line.Split(',');
}
foreach (var itParam in paramTokens)
{
functionSig += itParam;
if (!itParam.Contains(')'))
{
functionSig += ",";
}
}
if (line.Contains(')'))
{
foundEndOfSignature = true;
}
line = reader.ReadLine();
}
functionInvoc = CreateInvocationFromString(functionSig);
//Ok, now if we have founc the signature, iterate throug the file until we find the found
//of the function
bool foundEndOfBody = false;
int braceCount = 0;
while (!foundEndOfBody)
{
functionBody += line;
if (line.Contains('{'))
{
braceCount++;
}
if (line.Contains('}'))
{
braceCount--;
}
if (braceCount == 0)
{
foundEndOfBody = true;
//Remove first and last brace
int pos = -1;
for (int i = 0; i < functionBody.Length; i++)
{
if (functionBody[i] == '{')
{
pos = i;
break;
}
}
functionBody.Remove(pos, 1);
this.functionCacheMap.Add(functionInvoc, functionBody);
}
functionBody += "\n";
line = reader.ReadLine();
}
}
}
}
}
reader.Close();
}
19
Source : AyFuncHttp.cs
with MIT License
from ay2015
with MIT License
from ay2015
public string PostData<T>(string url, T model, string filter = "")
{
string postData = BuildPostData<T>(model, filter);
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes(postData);
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
myRequest.Method = "POST";
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.ContentLength = data.Length;
Stream newStream = myRequest.GetRequestStream();
newStream.Write(data, 0, data.Length);
newStream.Close();
HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.Default);
string content = reader.ReadToEnd();
reader.Close();
return content;
}
19
Source : AyFuncHttp.cs
with MIT License
from ay2015
with MIT License
from ay2015
public string PostDataPartial<T>(string url, T model, string condition = "")
{
string postData = BuildPostDataPartial<T>(model, condition);
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes(postData);
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
myRequest.Method = "POST";
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.ContentLength = data.Length;
Stream newStream = myRequest.GetRequestStream();
newStream.Write(data, 0, data.Length);
newStream.Close();
HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.Default);
string content = reader.ReadToEnd();
reader.Close();
return content;
}
19
Source : AyFuncHttp.cs
with MIT License
from ay2015
with MIT License
from ay2015
private string GetResponsereplacedtring(HttpWebResponse rsp, Encoding encoding)
{
StringBuilder result = new StringBuilder();
Stream stream = null;
StreamReader reader = null;
try
{
// 以字符流的方式读取HTTP响应
stream = rsp.GetResponseStream();
reader = new StreamReader(stream, encoding);
// 每次读取不大于256个字符,并写入字符串
char[] buffer = new char[256];
int readBytes = 0;
while ((readBytes = reader.Read(buffer, 0, buffer.Length)) > 0)
{
result.Append(buffer, 0, readBytes);
}
}
catch (WebException webEx)
{
if (webEx.Status == WebExceptionStatus.Timeout)
{
result = new StringBuilder();
}
}
finally
{
// 释放资源
if (reader != null) reader.Close();
if (stream != null) stream.Close();
if (rsp != null) rsp.Close();
}
return result.ToString();
}
19
Source : AyFuncHttp.cs
with MIT License
from ay2015
with MIT License
from ay2015
public string PostData(string url, string postData)
{
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes(postData);
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
myRequest.Method = "POST";
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.ContentLength = data.Length;
Stream newStream = myRequest.GetRequestStream();
newStream.Write(data, 0, data.Length);
newStream.Close();
HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.Default);
string content = reader.ReadToEnd();
reader.Close();
return content;
}
19
Source : AyAddress.cs
with MIT License
from ay2015
with MIT License
from ay2015
private static string GetBaiDuMapApiResult(string tag,int count)
{
string html = string.Empty;
string ak = "MLrSlgdxGi6DD9k8VfI4CNQ5vhYIzc7g"; //目前由个人账号申请,每天可调2000次,使用时请注意换掉
string url = string.Format("http://api.map.baidu.com/place/v2/search?q={0}®ion={1}&output=json&ak={2}&page_num={3}&page_size={4}",
GetQueryStrRandom(),
tag, ak, RandomNum(0, 400/count), //每次默认会搜出400条记录
count);
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
Encoding encoding = Encoding.UTF8;//根据网站的编码自定义
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader streamReader = new StreamReader(responseStream, encoding);
string retString = streamReader.ReadToEnd();
streamReader.Close();
responseStream.Close();
return retString;
}
catch (WebException ex)
{
throw new Exception(ex.Message);
}
}
19
Source : AboutWindow.cs
with MIT License
from azsumas
with MIT License
from azsumas
private void OnEnable()
{
string path = ScriptableObjectUtility.CinemachineInstallPath + "/ReleaseNotes.txt";
try
{
StreamReader reader = new StreamReader(path);
mReleaseNotes = reader.ReadToEnd();
reader.Close();
}
catch (System.Exception)
{
mReleaseNotes = path + " not found";
}
}
19
Source : ProcessRunner.cs
with MIT License
from Azure99
with MIT License
from Azure99
private string ReadStreamToEnd(StreamReader reader)
{
StringBuilder builder = new StringBuilder();
char[] buffer = new char[4096];
// 记录总输出长度
int sumLength = 0;
int len;
while ((len = reader.Read(buffer, 0, buffer.Length)) > 0)
{
builder.Append(buffer, 0, len);
sumLength += len;
if (sumLength > OutputLimit)
{
reader.Close();
return builder.ToString();
}
}
reader.Close();
return builder.ToString();
}
19
Source : JsonSerializer.cs
with MIT License
from AzureAD
with MIT License
from AzureAD
public Dictionary<string, object> ToJson()
{
Type type = this.dataContractValue.GetType();
DataContractJsonSerializer serializer =
new DataContractJsonSerializer(type, JsonSerializer.SerializerSettings.Value);
string json;
MemoryStream stream = null;
try
{
stream = new MemoryStream();
serializer.WriteObject(stream, this.dataContractValue);
stream.Position = 0;
StreamReader streamReader = null;
try
{
streamReader = new StreamReader(stream);
stream = null;
json = streamReader.ReadToEnd();
}
finally
{
if (streamReader != null)
{
streamReader.Close();
streamReader = null;
}
}
}
finally
{
if (stream != null)
{
stream.Close();
stream = null;
}
}
Dictionary<string, object> result = JsonFactory.Instance.Create(json, true);
return result;
}
19
Source : SchematizedMediaTypeFormatter.cs
with MIT License
from AzureAD
with MIT License
from AzureAD
private static async Task<string> ReadFromStream(Stream readStream)
{
if (null == readStream)
{
throw new ArgumentNullException(nameof(readStream));
}
StreamReader reader = null;
try
{
reader = new StreamReader(readStream, SchematizedMediaTypeFormatter.Encoding);
string result = await reader.ReadToEndAsync().ConfigureAwait(false);
return result;
}
finally
{
if (reader != null)
{
reader.Close();
reader = null;
}
}
}
19
Source : StandardCommandImpl.cs
with BSD 3-Clause "New" or "Revised" License
from b4rtik
with BSD 3-Clause "New" or "Revised" License
from b4rtik
public static void GetCat(string[] param)
{
try
{
if (File.Exists(param[0]))
{
using (StreamReader file = new StreamReader(param[0]))
{
int counter = 0;
string ln;
while ((ln = file.ReadLine()) != null)
{
Console.WriteLine("[*] {0}",ln);
counter++;
}
file.Close();
}
}
else
{
Console.WriteLine("[*] File not found {0}");
}
}
catch (Exception)
{
Console.WriteLine("[*] Error executing cat");
}
}
19
Source : GW2SkillAPIController.cs
with MIT License
from baaron4
with MIT License
from baaron4
private void SetAPISkills(string filePath)
{
if (File.Exists(filePath) && new FileInfo(filePath).Length != 0)
{
Console.WriteLine("Reading Skilllist");
using (var reader = new StreamReader(filePath))
{
var skillList = (List<GW2APISkill>)GW2APIUtilities.Deserializer.Deserialize(reader, typeof(List<GW2APISkill>));
_apiSkills = new GW2APIUtilities.APIItems<GW2APISkill>(skillList);
reader.Close();
}
}
else
{
_apiSkills = new GW2APIUtilities.APIItems<GW2APISkill>(GetGW2APISkills());
}
}
19
Source : GW2SpecAPIController.cs
with MIT License
from baaron4
with MIT License
from baaron4
private void SetAPISpecs(string filePath)
{
if (File.Exists(filePath) && new FileInfo(filePath).Length != 0)
{
Console.WriteLine("Reading SpecList");
using (var reader = new StreamReader(filePath))
{
var specList = (List<GW2APISpec>)GW2APIUtilities.Deserializer.Deserialize(reader, typeof(List<GW2APISpec>));
_apiSpecs = new GW2APIUtilities.APIItems<GW2APISpec>(specList);
reader.Close();
}
}
else
{
_apiSpecs = new GW2APIUtilities.APIItems<GW2APISpec>(GetGW2APISpecs());
}
}
19
Source : GW2TraitAPIController.cs
with MIT License
from baaron4
with MIT License
from baaron4
private void SetAPITraits(string filePath)
{
if (File.Exists(filePath) && new FileInfo(filePath).Length != 0)
{
Console.WriteLine("Reading Traitlist");
using (var reader = new StreamReader(filePath))
{
var traitList = (List<GW2APITrait>)GW2APIUtilities.Deserializer.Deserialize(reader, typeof(List<GW2APITrait>));
_apiTraits = new GW2APIUtilities.APIItems<GW2APITrait>(traitList);
reader.Close();
}
}
else
{
_apiTraits = new GW2APIUtilities.APIItems<GW2APITrait>(GetGW2APITraits());
}
}
19
Source : StartGame.cs
with MIT License
from baibao132
with MIT License
from baibao132
internal void errormonitoring()
{
Control.CheckForIllegalCrossThreadCalls = false;
StreamReader standardError = this.process.StandardError;
string sE = standardError.ReadToEnd();
if (sE != "")
{
Error error = new Error(null, sE);
if (this.ErrorEvent != null)
{
this.ErrorEvent(error);
}
else
{
standardError.Close();
}
}
try
{
this.process.WaitForExit();
standardError.Close();
this.process.Close();
}
catch (Exception)
{
}
}
19
Source : StartGame.cs
with MIT License
from baibao132
with MIT License
from baibao132
internal void monitoring()
{
try
{
Control.CheckForIllegalCrossThreadCalls = false;
StreamReader standardOutput = this.process.StandardOutput;
while (!standardOutput.EndOfStream)
{
string message = standardOutput.ReadLine();
if (WinAPI.GetHandle("LWJGL") == null && WinAPI.GetHandle("GLFW30") == null)
{
standardOutput.Close();
this.process.Close();
}
if (this.LogEvent != null)
{
this.LogEvent(new Log(message));
}
string str2 = this.SLC.Replace(message, "Exception", " ");
if ((str2 != null) && (str2 != message))
{
if (windows.WinAPI.GetHandle("LWJGL") == (IntPtr)0 && windows.WinAPI.GetHandle("GLFW30") == (IntPtr)0)
{
if (this.ErrorEvent != null)
{
this.ErrorEvent(new Error(null, standardOutput.ReadToEnd()));
}
}
}
if (this.ErrorEvent != null)
{
this.ErrorEvent(new Error(message, null));
}
}
this.process.WaitForExit();
standardOutput.Close();
this.process.Close();
}
catch (Exception)
{
}
}
19
Source : ErrorReporting.xaml.cs
with MIT License
from barry-jones
with MIT License
from barry-jones
private StringBuilder ReadErrorReportTemplate() {
StringBuilder content = new StringBuilder();
try {
object o = Application.Current.Resources;
System.Reflection.replacedembly a = System.Reflection.replacedembly.GetExecutingreplacedembly();
System.IO.StreamReader reader = new System.IO.StreamReader(
a.GetManifestResourceStream(string.Format("TheBoxSoftware.DeveloperSuite.LiveDoreplacedenter.Diagnostics.{0}", ErrorReporting.template))
);
content.Append(reader.ReadToEnd());
reader.Close();
}
finally { }
return content;
}
19
Source : UserApplicationStore.cs
with MIT License
from barry-jones
with MIT License
from barry-jones
public static void Load()
{
IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForreplacedembly();
using(IsolatedStorageFileStream fs = new IsolatedStorageFileStream("userpreferences.xml", System.IO.FileMode.OpenOrCreate, file))
{
if(fs != null)
{
System.IO.StreamReader reader = new System.IO.StreamReader(fs);
string preferenceData = string.Empty;
preferenceData = reader.ReadToEnd();
reader.Close();
// We are opening or creating, we could have no file present.
if(!string.IsNullOrEmpty(preferenceData.Trim()))
{
UserApplicationStore.store = (Model.UserApplicationStore)UserApplicationStore.DeSerialize(
preferenceData, typeof(Model.UserApplicationStore)
);
}
}
}
}
19
Source : MainForm.cs
with MIT License
from bestyize
with MIT License
from bestyize
private void Ts_menu_open_file_Click(object sender, EventArgs e)
{
var fileContent = string.Empty;
var filePath = string.Empty;
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog.FilterIndex = 1;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
filePath = openFileDialog.FileName;
var fileStream = openFileDialog.OpenFile();
StreamReader reader = new StreamReader(fileStream);
fileContent = reader.ReadToEnd();
reader.Close();
fileStream.Close();
tb_send.Text = fileContent;
}
}
19
Source : Auth.cs
with MIT License
from biitez
with MIT License
from biitez
internal string Decrypt(string cipherText)
{
try
{
var aes = new RijndaelManaged
{
Padding = PaddingMode.PKCS7,
Mode = CipherMode.CBC,
KeySize = 256,
Key = EncryptionKey,
IV = EncryptionIv
};
var decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
var msDecrypt = new MemoryStream(BaseConverters.FromUrlSafeBase64(cipherText));
var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);
var srDecrypt = new StreamReader(csDecrypt);
var plaintext = srDecrypt.ReadToEnd();
srDecrypt.Close();
csDecrypt.Close();
msDecrypt.Close();
aes.Clear();
return plaintext;
}
catch
{
throw new CryptographicException("There was a problem decrypting the message from the server, if this continues, contact a support!");
}
}
19
Source : Program.cs
with MIT License
from blockcoli
with MIT License
from blockcoli
void AccountRecover(string[] cmd)
{
Console.WriteLine(">> Recovering Wallet");
if (cmd.Length <= 2)
{
Console.WriteLine("[ERROR] Error recovering Libra wallet: Invalid number of arguments for recovering wallets");
return;
}
var fileName = cmd[2];
if (!File.Exists(fileName))
{
Console.WriteLine("[ERROR] Error recovering Libra wallet: LibraWalletGeneric: No such file or directory (os error 2)");
return;
}
var reader = new StreamReader(fileName);
var words = reader.ReadLine().Split(';');
reader.Close();
if (words.Length <= 1)
{
Console.WriteLine("[ERROR] Error recovering Libra wallet: LibraWalletGeneric: Invalid entry");
return;
}
Console.WriteLine($"Wallet recovered and the first {words[1]} child accounts were derived");
wallet = new LibraWallet(words[0]);
for (int i = 0; i < int.Parse(words[1]); i++)
{
var account = wallet.NewAccount();
Console.WriteLine($"#{i} address {account.Address}");
}
}
19
Source : LanguageCommand.cs
with GNU General Public License v3.0
from BlowaXD
with GNU General Public License v3.0
from BlowaXD
private static void ReadFileAndFillService(string file, LanguageKey key)
{
int i = 0;
using (var langFileStream = new StreamReader(file, key.GetEncoding()))
{
string line;
while ((line = langFileStream.ReadLine()) != null)
{
string[] linesave = line.Split('\t');
if (linesave.Length <= 1)
{
continue;
}
i++;
_langs.SetLanguage(linesave[0], linesave[1], key);
_langs.SetLanguage(linesave[1], linesave[0], key);
}
langFileStream.Close();
}
Log.Info($"{file} : {i} language keys updated");
}
19
Source : RESTLayer_DEPRECATED.cs
with MIT License
from blueherongis
with MIT License
from blueherongis
protected override void SolveInstance(IGH_DataAccess DA)
{
string URL = string.Empty;
DA.GetData<string>("Service URL", ref URL);
//get json from rest service
string restquery = URL + "?f=pjson";
System.Net.HttpWebRequest req = System.Net.WebRequest.Create(restquery) as System.Net.HttpWebRequest;
string result = null;
using (System.Net.HttpWebResponse resp = req.GetResponse() as System.Net.HttpWebResponse)
{
System.IO.StreamReader reader = new System.IO.StreamReader(resp.GetResponseStream());
result = reader.ReadToEnd();
reader.Close();
}
//parse json into a description and list of layer values
JObject j = JObject.Parse(result);
List<string> layerKey = new List<string>();
List<int> layerInt = new List<int>();
Dictionary<string, int> d = new Dictionary<string, int>();
for (int i = 1; i < j["layers"].Children()["name"].Count(); i++)
{
d[(string)j["layers"][i]["name"]] = (int)j["layers"][i]["id"];
layerKey.Add((string)j["layers"][i]["name"]);
layerInt.Add((int)j["layers"][i]["id"]);
}
DA.SetData("Map Description", (string)j["description"]);
//mapDescription = (string) j["description"];
DA.SetDataList("Map Layer", layerKey);
//mapLayer = layerKey;
DA.SetDataList("Map Integer", layerInt);
//mapInt = layerInt;
}
19
Source : RESTLayer.cs
with MIT License
from blueherongis
with MIT License
from blueherongis
protected override void SolveInstance(IGH_DataAccess DA)
{
string URL = string.Empty;
DA.GetData<string>("Service URL", ref URL);
if (!URL.EndsWith(@"/")) { URL = URL + "/"; }
//get json from rest service
string restquery = URL + "?f=pjson";
System.Net.HttpWebRequest req = System.Net.WebRequest.Create(restquery) as System.Net.HttpWebRequest;
string result = null;
using (System.Net.HttpWebResponse resp = req.GetResponse() as System.Net.HttpWebResponse)
{
System.IO.StreamReader reader = new System.IO.StreamReader(resp.GetResponseStream());
result = reader.ReadToEnd();
reader.Close();
}
//parse json into a description and list of layer values
JObject j = JObject.Parse(result);
List<string> layerKey = new List<string>();
List<int> layerInt = new List<int>();
List<string> layerUrl = new List<string>();
Dictionary<string, int> d = new Dictionary<string, int>();
for (int i = 1; i < j["layers"].Children()["name"].Count(); i++)
{
d[(string)j["layers"][i]["name"]] = (int)j["layers"][i]["id"];
layerKey.Add((string)j["layers"][i]["name"]);
layerInt.Add((int)j["layers"][i]["id"]);
layerUrl.Add(URL + j["layers"][i]["id"].ToString() + "/");
}
DA.SetData(0, (string)j["description"]);
//mapDescription = (string) j["description"];
DA.SetDataList(1, layerKey);
//mapLayer = layerKey;
DA.SetDataList(2, layerInt);
//mapInt = layerInt;
DA.SetDataList(3, layerUrl);
}
19
Source : RESTRevGeo.cs
with MIT License
from blueherongis
with MIT License
from blueherongis
public static string GetData(string qst)
{
System.Net.HttpWebRequest req = System.Net.WebRequest.Create(qst) as System.Net.HttpWebRequest;
string result = null;
try
{
using (System.Net.HttpWebResponse resp = req.GetResponse() as System.Net.HttpWebResponse)
{
System.IO.StreamReader reader = new System.IO.StreamReader(resp.GetResponseStream());
result = reader.ReadToEnd();
reader.Close();
}
}
catch
{
return "Something went wrong getting data from the Service";
}
return result;
}
19
Source : Convert.cs
with MIT License
from blueherongis
with MIT License
from blueherongis
public static string HttpToJson(string URL)
{
//need to update for https issues
//GH forum issue: https://www.grreplacedhopper3d.com/group/heron/forum/topics/discover-rest-data-sources?commentId=2985220%3AComment%3A1945956&xg_source=msg_com_gr_forum
//solution found here: https://stackoverflow.com/questions/2859790/the-request-was-aborted-could-not-create-ssl-tls-secure-channel
//add these two lines of code
System.Net.ServicePointManager.Expect100Continue = true;
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
//get json from rest service
System.Net.HttpWebRequest req = System.Net.WebRequest.Create(URL) as System.Net.HttpWebRequest;
string result = null;
using (System.Net.HttpWebResponse resp = req.GetResponse() as System.Net.HttpWebResponse)
{
System.IO.StreamReader reader = new System.IO.StreamReader(resp.GetResponseStream());
result = reader.ReadToEnd();
reader.Close();
}
return result;
}
19
Source : iFruitContact.cs
with MIT License
from Bob74
with MIT License
from Bob74
private void UpdateContactIndex()
{
// Warning: new iFruitContact(...) can be called before iFruitAddon2 is initialized.
// That's why it is important not to rely on static variables inside the iFruitAddon2 clreplaced.
string tempFile = iFruitAddon2.GetTempFilePath();
if (File.Exists(tempFile))
{
// Not the first launch
bool written = false;
while (!written)
{
try
{
// We need to check if the file is unlocked and then get the value and write the new one.
int index;
StreamReader sr = new StreamReader(tempFile);
if (int.TryParse(sr.ReadLine().Trim(new char[] { '\r', '\n', ' ' }), out index))
iFruitAddon2.ContactIndex = index;
sr.Close();
StreamWriter file = new StreamWriter(tempFile);
file.WriteLine(iFruitAddon2.ContactIndex + 1);
file.Close();
written = true;
}
catch (IOException)
{
// The file is locked when StreamReader or StreamWriter has opend it.
// The current instance of iFruitAddon2 must wait until the file is released.
}
catch (Exception ex)
{
// Unknown error occured
Logger.Log(ex.Message);
written = true;
}
}
}
else
{
// First launch. We create the file
StreamWriter file = new StreamWriter(tempFile);
file.Write(iFruitAddon2.ContactIndex + 1);
file.Close();
}
}
19
Source : BoletoBancario.cs
with MIT License
from BoletoNet
with MIT License
from BoletoNet
protected static void HtmlOfflineHeader(StringBuilder html, bool usaCsspdf = false)
{
html.Append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n");
html.Append("<html xmlns=\"http://www.w3.org/1999/xhtml\">\n");
html.Append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n");
html.Append("<meta charset=\"utf-8\"/>\n");
html.Append("<head>");
html.Append(" <replacedle>Boleto.Net</replacedle>\n");
#region Css
{
var arquivoCss = usaCsspdf ? "BoletoNetCore.BoletoImpressao.BoletoNetPDF.css" : "BoletoNetCore.BoletoImpressao.BoletoNet.css";
var stream = replacedembly.GetExecutingreplacedembly().GetManifestResourceStream(arquivoCss);
using (var sr = new StreamReader(stream))
{
html.Append("<style>\n");
html.Append(sr.ReadToEnd());
html.Append("</style>\n");
sr.Close();
sr.Dispose();
}
}
#endregion Css
html.Append(" </head>\n");
html.Append("<body>\n");
}
19
Source : Worker.cs
with MIT License
from botman99
with MIT License
from botman99
private string ReadLine(StreamReader sr) // read a line of text from the input stream (we use this instead of StreamReader.ReadLine() so we can cancel a search easier)
{
int i;
currentline.Clear();
while( (i = sr.Read()) > 0 )
{
if( Globals.bShouldStopWorkerJobs )
{
sr.Close();
return "";
}
if( i == 13 ) // if character is a carriage return
{
int next_char = sr.Peek();
if( next_char == 10 ) // if CR followed by LF
{
sr.Read(); // throw away the newline
}
break;
}
else if( i == 10 )
{
break;
}
char c = (char)i;
currentline.Append(c);
if( currentline.Length == MAX_LINE_LENGTH )
{
while( (i = sr.Read()) > 0 ) // read until we get an end of line character
{
if( Globals.bShouldStopWorkerJobs )
{
sr.Close();
return "";
}
if( i == 13 ) // if character is a carriage return
{
int next_char = sr.Peek();
if( next_char == 10 ) // if CR followed by LF
{
sr.Read(); // throw away the newline
}
break;
}
else if( i == 10 )
{
break;
}
}
break;
}
}
return currentline.ToString();
}
19
Source : Worker.cs
with MIT License
from botman99
with MIT License
from botman99
private bool ScanFileForMatches(string Filename) // scan through the specified file to look for search text matches
{
Regex regex = null;
if( Globals.bRegEx )
{
regex = new Regex(Globals.SearchString, Globals.bCaseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase);
}
StreamReader sr = null;
try
{
sr = new StreamReader(Filename,true);
}
catch( Exception e )
{
Console.WriteLine("ScanFileForMatches() Exception: {0}", e.Message);
return false;
}
bool bFoundMatchInFile = false;
int LineNumber = 0;
int NumberOfMatchesInFile = 0;
string[] PreviewLines = new string[5]; // circular buffer of preview lines (for displaying before and after matches)
int PreviewLineIndex = -1; // we haven't added a line to the circular buffer yet
int PreviewLineCount = 0; // number of lines in the preview circular buffer that are valid
int LinesSinceMatch = -1; // reset this to 0 when we find a match so we know when to store "after" preview lines following a match
string line = "";
while (!Globals.bShouldStopWorkerJobs && (sr.Peek() >= 0))
{
line = ReadLine(sr);
LineNumber++;
ReadLineSleepCount++;
if( ReadLineSleepCount >= 1000 )
{
ReadLineSleepCount = 0;
Thread.Sleep(0); // force context switch
}
int MatchesInLine = 0;
if( Globals.bRegEx && (regex != null) )
{
MatchCollection matches = regex.Matches(line);
MatchesInLine = matches.Count;
if( matches.Count > 0 )
{
List<MatchPos> Matches = new List<MatchPos>();
for( int i = 0; i < matches.Count; i++ )
{
MatchPos Match = new MatchPos(matches[i].Index, matches[i].Length);
Matches.Add(Match);
}
AddMatchLine(ref line, ref Matches, ref PreviewLines, ref PreviewLineIndex, ref PreviewLineCount, ref LineNumber, ref LinesSinceMatch);
}
}
else
{
int pos = line.IndexOf(Globals.SearchString, 0, Globals.bCaseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase);
if( pos >= 0 )
{
List<MatchPos> Matches = new List<MatchPos>();
while( pos >= 0 )
{
if( Globals.bShouldStopWorkerJobs )
{
sr.Close();
return false;
}
MatchesInLine++;
MatchPos Match = new MatchPos(pos, Globals.SearchString.Length);
Matches.Add(Match);
if( pos < (line.Length - 1) )
{
pos = line.IndexOf(Globals.SearchString, pos+1, Globals.bCaseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase);
}
else
{
pos = -1;
}
}
AddMatchLine(ref line, ref Matches, ref PreviewLines, ref PreviewLineIndex, ref PreviewLineCount, ref LineNumber, ref LinesSinceMatch);
}
}
if( MatchesInLine > 0 )
{
bFoundMatchInFile = true;
}
else // if no matches, add this line to the circular preview buffer
{
PreviewLineIndex = (PreviewLineIndex + 1) % 5;
PreviewLines[PreviewLineIndex] = line;
PreviewLineCount = Math.Min(PreviewLineCount + 1, 5);
if( LinesSinceMatch >= 0 )
{
LinesSinceMatch++;
try
{
if( (LinesSinceMatch == 5) || (sr.Peek() == -1) ) // if we're read 5 lines or reached the end of the file...
{
int PreviewIndex = PreviewLineIndex - (PreviewLineCount - 1); // index in the circular buffer of the oldest preview line
if( PreviewIndex < 0 )
{
PreviewIndex += 5;
}
for( int index = 0; index < PreviewLineCount; index++ )
{
Globals.SearchLine PreviewSearchLine = new Globals.SearchLine();
PreviewSearchLine.LineNumber = LineNumber - (PreviewLineCount - index) + 1;
PreviewSearchLine.Line = PreviewLines[PreviewIndex++];
if( PreviewIndex == 5 )
{
PreviewIndex = 0;
}
PreviewSearchLine.bIsSearchTextMatch = false;
Globals.SearchFiles[SearchFilesIndex].Lines.Add(PreviewSearchLine);
}
PreviewLineIndex = -1; // reset the circular buffer
PreviewLineCount = 0;
LinesSinceMatch = -1;
}
}
catch( Exception e )
{
Console.WriteLine("ScanFileForMatches() Exception: {0}", e.Message);
}
}
}
NumberOfMatchesInFile += MatchesInLine;
}
try
{
sr.Close();
}
catch( Exception e )
{
Console.WriteLine("ScanFileForMatches() Exception: {0}", e.Message);
}
if (Globals.bShouldStopWorkerJobs)
{
return false;
}
Globals.SearchFiles[SearchFilesIndex].SearchMatchCount = NumberOfMatchesInFile;
return bFoundMatchInFile;
}
19
Source : SimpleHttpServer.cs
with MIT License
from bp2008
with MIT License
from bp2008
private void handlePOSTRequest()
{
try
{
int content_len = 0;
MemoryStream ms = new MemoryStream();
string content_length_str = GetHeaderValue("Content-Length");
if (!string.IsNullOrWhiteSpace(content_length_str))
{
if (int.TryParse(content_length_str, out content_len))
{
if (content_len > MAX_POST_SIZE)
{
this.writeFailure("413 Request Enreplacedy Too Large", "Request Too Large");
SimpleHttpLogger.LogVerbose("POST Content-Length(" + content_len + ") too big for this simple server. Server can handle up to " + MAX_POST_SIZE);
return;
}
byte[] buf = new byte[BUF_SIZE];
int to_read = content_len;
while (to_read > 0)
{
int numread = this.inputStream.Read(buf, 0, Math.Min(BUF_SIZE, to_read));
if (numread == 0)
{
if (to_read == 0)
break;
else
{
SimpleHttpLogger.LogVerbose("client disconnected during post");
return;
}
}
to_read -= numread;
ms.Write(buf, 0, numread);
}
ms.Seek(0, SeekOrigin.Begin);
}
}
else
{
this.writeFailure("411 Length Required", "The request did not specify the length of its content.");
SimpleHttpLogger.LogVerbose("The request did not specify the length of its content. This server requires that all POST requests include a Content-Length header.");
return;
}
string contentType = GetHeaderValue("Content-Type");
if (contentType != null && contentType.Contains("application/x-www-form-urlencoded"))
{
StreamReader sr = new StreamReader(ms);
string all = sr.ReadToEnd();
sr.Close();
RawPostParams = ParseQueryStringArguments(all, false, true);
PostParams = ParseQueryStringArguments(all, false);
srv.handlePOSTRequest(this, null);
}
else
{
srv.handlePOSTRequest(this, new StreamReader(ms));
}
}
finally
{
try
{
if (!responseWritten)
this.writeFailure();
}
catch (Exception) { }
}
}
19
Source : Playlist.cs
with GNU General Public License v3.0
from BRH-Media
with GNU General Public License v3.0
from BRH-Media
public string[] Open(string playlist)
{
List<string> fileNames = null;
if (string.IsNullOrWhiteSpace(playlist))
{
_base._lastError = HResult.ERROR_INVALID_NAME;
}
else
{
bool validExtension = false;
bool m3u8 = false;
string extension = Path.GetExtension(playlist);
if (extension.Length == 0)
{
playlist += ".m3u";
validExtension = true;
}
else if (string.Equals(extension, ".m3u", StringComparison.OrdinalIgnoreCase) || (string.Equals(extension, ".ppl", StringComparison.OrdinalIgnoreCase)))
{
validExtension = true;
}
else if (string.Equals(extension, ".m3u8", StringComparison.OrdinalIgnoreCase))
{
validExtension = true;
m3u8 = true;
}
if (validExtension)
{
if (File.Exists(playlist))
{
StreamReader file = null;
string playListPath = Path.GetDirectoryName(playlist);
string line;
fileNames = new List<string>(16);
try
{
if (m3u8) file = new StreamReader(playlist, Encoding.UTF8);
else file = new StreamReader(playlist); // something wrong with Encoding.Default?
while ((line = file.ReadLine()) != null)
{
line = line.TrimStart();
// skip if line is empty, #extm3u, #extinf info or # comment
//if (line != string.Empty && line[0] != '#')
if (line.Length > 0 && line[0] != '#')
{
// get absolute path...
if (line[1] != ':' && !line.Contains(@"://") && !line.Contains(@":\\")) fileNames.Add(Path.GetFullPath(Path.Combine(playListPath, line)));
else fileNames.Add(line);
}
}
_base._lastError = Player.NO_ERROR;
}
catch (Exception e) { _base._lastError = (HResult)Marshal.GetHRForException(e); }
if (file != null) file.Close();
}
else _base._lastError = HResult.ERROR_FILE_NOT_FOUND;
}
else _base._lastError = HResult.ERROR_INVALID_NAME;
}
if (fileNames == null || fileNames.Count == 0) return null;
return fileNames.ToArray();
}
19
Source : Subtitles.cs
with GNU General Public License v3.0
from BRH-Media
with GNU General Public License v3.0
from BRH-Media
private bool Subreplacedles_GetFromFile(string fileName)
{
bool result = false;
if (!string.IsNullOrWhiteSpace(fileName))
{
StreamReader reader = new StreamReader(fileName, st_Encoding, true);
int count = Subreplacedles_Count(reader);
reader.Close();
if (count > 0)
{
bool error = false;
int readStep = 0;
Match m;
string line;
TimeSpan startTime = TimeSpan.Zero;
TimeSpan endTime = TimeSpan.Zero;
string text = "";
int index = 0;
st_SubreplacedleItems = new SubreplacedleItem[count];
// use new reader because of problems with files with BOM
reader = new StreamReader(fileName, st_Encoding, true);
while ((line = (reader.ReadLine())) != null && !error)
{
line = line.Trim();
if (string.IsNullOrWhiteSpace(line)) continue;
int testId;
switch (readStep)
{
case 0: // Id
#pragma warning disable IDE0059 // Unnecessary replacedignment of a value
if (int.TryParse(line, out testId))
{
readStep = 1;
}
break;
case 1: // Time
m = st_TimeRegex.Match(line);
if (m.Success)
{
if (!TimeSpan.TryParse(m.Groups["start"].Value.Replace(",", "."), out startTime)) error = true;
if (!TimeSpan.TryParse(m.Groups["end"].Value.Replace(",", "."), out endTime)) error = true;
}
else error = true;
readStep = 2;
break;
case 2: // Text
if (int.TryParse(line, out testId)) // if not id (subreplacedle number)
#pragma warning restore IDE0059 // Unnecessary replacedignment of a value
{
if (st_RemoveHTMLTags) st_SubreplacedleItems[index++] = new SubreplacedleItem(startTime.Ticks, endTime.Ticks, st_TagsRegex.Replace(text, string.Empty));
else st_SubreplacedleItems[index++] = new SubreplacedleItem(startTime.Ticks, endTime.Ticks, text);
text = "";
readStep = 1;
}
else
{
text += line + "\r\n";
}
break;
}
}
if (!error)
{
if (text.Length > 0)
{
if (st_RemoveHTMLTags) st_SubreplacedleItems[index++] = new SubreplacedleItem(startTime.Ticks, endTime.Ticks, st_TagsRegex.Replace(text, string.Empty));
else st_SubreplacedleItems[index++] = new SubreplacedleItem(startTime.Ticks, endTime.Ticks, text);
}
else
{
st_SubreplacedleItems[index++] = new SubreplacedleItem(0, 0, string.Empty);
}
st_SubreplacedleCount = count;
if (st_SubreplacedleItems[st_SubreplacedleCount - 1] == null)
{
if (st_SubreplacedleCount > 1) st_SubreplacedleItems[st_SubreplacedleCount - 1] = st_SubreplacedleItems[st_SubreplacedleCount - 2];
else st_SubreplacedleItems[st_SubreplacedleCount - 1] = new SubreplacedleItem(0, 0, string.Empty);
}
result = true;
}
reader.Close();
}
}
return result;
}
See More Examples