Here are the examples of the csharp api System.IO.File.Open(string, System.IO.FileMode) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
999 Examples
19
View Source File : StaticFiles.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public static IApplicationBuilder UseFreeAdminLteStaticFiles(this IApplicationBuilder app, string requestPathBase) {
if (_isStaticFiles == false) {
lock (_isStaticFilesLock) {
if (_isStaticFiles == false) {
var curPath = AppDomain.CurrentDomain.BaseDirectory;
var zipPath = $"{curPath}/{Guid.NewGuid()}.zip";
using (var zip = WwwrootStream()) {
using (var fs = File.Open(zipPath, FileMode.OpenOrCreate)) {
zip.CopyTo(fs);
fs.Close();
}
zip.Close();
}
var wwwrootPath = Path.Combine(curPath, "FreeSql.AdminLTE.wwwroot");
if (Directory.Exists(wwwrootPath)) Directory.Delete(wwwrootPath, true);
try {
System.IO.Compression.ZipFile.ExtractToDirectory(zipPath, wwwrootPath, Encoding.UTF8);
} catch (Exception ex) {
throw new Exception($"UseFreeAdminLtePreview 错误,资源文件解压失败:{ex.Message}", ex);
} finally {
File.Delete(zipPath);
}
app.UseStaticFiles(new StaticFileOptions {
RequestPath = requestPathBase.TrimEnd('/'),
FileProvider = new PhysicalFileProvider(wwwrootPath)
});
_isStaticFiles = true;
}
}
}
return app;
}
19
View Source File : ExtendableEnums.cs
License : MIT License
Project Creator : 7ark
License : MIT License
Project Creator : 7ark
static void AddNewEnum(string clreplacedFile, string path, string enumName, string newEnum)
{
string[] originalSplit = clreplacedFile.Split(new[] { "enum " + enumName }, System.StringSplitOptions.RemoveEmptyEntries);
string newHalf = originalSplit[1];
string enumSection = newHalf.Split('}')[0];
string[] commas = enumSection.Split(',');
if (commas.Length == 0 && enumSection.Split('{')[0].Trim().Length == 0) //They've left the enum empty... for some reason.
{
Debug.Log("Uhh idk yet");
newHalf = newHalf.Replace(enumSection, enumSection + newEnum);
}
else
{
bool commaAfter = commas[commas.Length - 1].Trim().Length == 0; //This should check if they added a comma after their last enum value.
if (commaAfter)
{
newHalf = newHalf.Replace(enumSection, enumSection + newEnum + ", ");
}
else
{
while (enumSection.Length > 0 && enumSection[enumSection.Length - 1] == ' ')
enumSection = enumSection.Substring(0, enumSection.Length - 1);
newHalf = newHalf.Replace(enumSection, enumSection + ", " + newEnum);
}
}
string result = clreplacedFile.Replace(originalSplit[1], newHalf);
using (var file = File.Open(path, FileMode.Create))
{
using (var writer = new StreamWriter(file))
{
writer.Write(result);
}
}
replacedetDatabase.Refresh();
}
19
View Source File : Utility.IO.cs
License : MIT License
Project Creator : 7Bytes-Studio
License : MIT License
Project Creator : 7Bytes-Studio
public static void SaveFile(string filePath,byte[] data,Action saveCompleteCallback)
{
var fs = File.Open(filePath, FileMode.Create);
fs.BeginWrite(data, 0, data.Length, new AsyncCallback(iar =>
{
using (var _fs = iar.AsyncState as FileStream)
{
_fs.EndWrite(iar);
if (null!=saveCompleteCallback)
{
saveCompleteCallback.Invoke();
}
}
}), fs);
}
19
View Source File : WebServer.cs
License : Apache License 2.0
Project Creator : A7ocin
License : Apache License 2.0
Project Creator : A7ocin
void OnGetContext(IAsyncResult async)
{
// start listening for the next request
_listener.BeginGetContext(OnGetContext, null);
var context = _listener.EndGetContext(async);
try
{
if (context.Request.RawUrl == "/")
{
Debug.Log("[WebServer] context.Request.RawUrl");
context.Response.StatusCode = 200;
var process = System.Diagnostics.Process.GetCurrentProcess();
string msg = string.Format(@"<html><body><h1>UMA Simple Web Server</h1><table>
<tr><td>Host Application</td><td>{0} (Process Id: {1})</td></tr>
<tr><td>Working Directory</td><td>{2}</td></tr>
</table><br><br>{3}</body></html>", process.ProcessName, process.Id, System.IO.Directory.GetCurrentDirectory(), GetLog("<br>"));
var data = System.Text.Encoding.UTF8.GetBytes(msg);
context.Response.OutputStream.Write(data, 0, data.Length);
context.Response.OutputStream.Close();
//Tried adding response close aswell like in Adamas original
context.Response.Close();
}
else
{
var filePath = System.IO.Path.Combine(_hostedFolder, context.Request.RawUrl.Substring(1));
if (System.IO.File.Exists(filePath))
{
using (var file = System.IO.File.Open(filePath, System.IO.FileMode.Open))
{
var buffer = new byte[file.Length];
file.Read(buffer, 0, (int)file.Length);
context.Response.ContentLength64 = file.Length;
context.Response.StatusCode = 200;
context.Response.OutputStream.Write(buffer, 0, (int)file.Length);
}
}
else
{
context.Response.StatusCode = 404;
UnityEngine.Debug.LogErrorFormat("Url not served. Have you built your replacedet Bundles? Url not served from: {0} '{1}'", context.Request.RawUrl, filePath);
#if UNITY_EDITOR
replacedetBundleManager.SimulateOverride = true;
context.Response.OutputStream.Close();
//Tried adding response close aswell like in Adamas original
context.Response.Abort();
return;
#endif
}
}
lock (_requestLog)
{
_requestLog.Add(string.Format("{0} {1}", context.Response.StatusCode, context.Request.Url));
}
context.Response.OutputStream.Close();
context.Response.Close();
}
catch (HttpListenerException e)
{
if (e.ErrorCode == -2147467259)
{
// shutdown, terminate silently
Debug.LogWarning("[Web Server] ErrorCode -2147467259: terminate silently");
context.Response.Abort();
return;
}
UnityEngine.Debug.LogException(e);
context.Response.Abort();
}
catch (Exception e)
{
UnityEngine.Debug.LogException(e);
context.Response.Abort();
}
}
19
View Source File : GltfUtility.cs
License : Apache License 2.0
Project Creator : abist-co-ltd
License : Apache License 2.0
Project Creator : abist-co-ltd
public static async Task<GltfObject> ImportGltfObjectFromPathAsync(string uri)
{
if (!SyncContextUtility.IsMainThread)
{
Debug.LogError("ImportGltfObjectFromPathAsync must be called from the main thread!");
return null;
}
if (string.IsNullOrWhiteSpace(uri))
{
Debug.LogError("Uri is not valid.");
return null;
}
GltfObject gltfObject;
bool useBackgroundThread = Application.isPlaying;
if (useBackgroundThread) { await BackgroundThread; }
if (uri.EndsWith(".gltf", StringComparison.OrdinalIgnoreCase))
{
string gltfJson = File.ReadAllText(uri);
gltfObject = GetGltfObjectFromJson(gltfJson);
if (gltfObject == null)
{
Debug.LogError("Failed load Gltf Object from json schema.");
return null;
}
}
else if (uri.EndsWith(".glb", StringComparison.OrdinalIgnoreCase))
{
byte[] glbData;
#if WINDOWS_UWP
if (useBackgroundThread)
{
try
{
var storageFile = await StorageFile.GetFileFromPathAsync(uri);
if (storageFile == null)
{
Debug.LogError($"Failed to locate .glb file at {uri}");
return null;
}
var buffer = await FileIO.ReadBufferAsync(storageFile);
using (DataReader dataReader = DataReader.FromBuffer(buffer))
{
glbData = new byte[buffer.Length];
dataReader.ReadBytes(glbData);
}
}
catch (Exception e)
{
Debug.LogError(e.Message);
return null;
}
}
else
{
glbData = UnityEngine.Windows.File.ReadAllBytes(uri);
}
#else
using (FileStream stream = File.Open(uri, FileMode.Open))
{
glbData = new byte[stream.Length];
if (useBackgroundThread)
{
await stream.ReadAsync(glbData, 0, (int)stream.Length);
}
else
{
stream.Read(glbData, 0, (int)stream.Length);
}
}
#endif
gltfObject = GetGltfObjectFromGlb(glbData);
if (gltfObject == null)
{
Debug.LogError("Failed to load GlTF Object from .glb!");
return null;
}
}
else
{
Debug.LogError("Unsupported file name extension.");
return null;
}
gltfObject.Uri = uri;
try
{
gltfObject.Name = Path.GetFileNameWithoutExtension(uri);
}
catch (ArgumentException)
{
Debug.LogWarning("Uri contained invalid character");
gltfObject.Name = DefaultObjectName;
}
gltfObject.UseBackgroundThread = useBackgroundThread;
await gltfObject.ConstructAsync();
if (gltfObject.GameObjectReference == null)
{
Debug.LogError("Failed to construct Gltf Object.");
}
if (useBackgroundThread) { await Update; }
return gltfObject;
}
19
View Source File : ConstructGltf.cs
License : Apache License 2.0
Project Creator : abist-co-ltd
License : Apache License 2.0
Project Creator : abist-co-ltd
private static async Task ConstructTextureAsync(this GltfObject gltfObject, GltfTexture gltfTexture)
{
if (gltfObject.UseBackgroundThread) await BackgroundThread;
if (gltfTexture.source >= 0)
{
GltfImage gltfImage = gltfObject.images[gltfTexture.source];
byte[] imageData = null;
Texture2D texture = null;
if (!string.IsNullOrEmpty(gltfObject.Uri) && !string.IsNullOrEmpty(gltfImage.uri))
{
var parentDirectory = Directory.GetParent(gltfObject.Uri).FullName;
var path = Path.Combine(parentDirectory, gltfImage.uri);
#if UNITY_EDITOR
if (gltfObject.UseBackgroundThread) await Update;
var projectPath = Path.GetFullPath(path).Replace(Path.GetFullPath(Application.dataPath), "replacedets");
texture = UnityEditor.replacedetDatabase.LoadreplacedetAtPath<Texture2D>(projectPath);
if (gltfObject.UseBackgroundThread) await BackgroundThread;
#endif
if (texture == null)
{
#if WINDOWS_UWP
if (gltfObject.UseBackgroundThread)
{
try
{
var storageFile = await StorageFile.GetFileFromPathAsync(path);
if (storageFile != null)
{
var buffer = await FileIO.ReadBufferAsync(storageFile);
using (DataReader dataReader = DataReader.FromBuffer(buffer))
{
imageData = new byte[buffer.Length];
dataReader.ReadBytes(imageData);
}
}
}
catch (Exception e)
{
Debug.LogError(e.Message);
}
}
else
{
imageData = UnityEngine.Windows.File.ReadAllBytes(path);
}
#else
using (FileStream stream = File.Open(path, FileMode.Open))
{
imageData = new byte[stream.Length];
if (gltfObject.UseBackgroundThread)
{
await stream.ReadAsync(imageData, 0, (int)stream.Length);
}
else
{
stream.Read(imageData, 0, (int)stream.Length);
}
}
#endif
}
}
else
{
var imageBufferView = gltfObject.bufferViews[gltfImage.bufferView];
imageData = new byte[imageBufferView.byteLength];
Array.Copy(imageBufferView.Buffer.BufferData, imageBufferView.byteOffset, imageData, 0, imageData.Length);
}
if (texture == null)
{
if (gltfObject.UseBackgroundThread) await Update;
// TODO Load texture async
texture = new Texture2D(2, 2);
gltfImage.Texture = texture;
gltfImage.Texture.LoadImage(imageData);
}
else
{
gltfImage.Texture = texture;
}
gltfTexture.Texture = texture;
if (gltfObject.UseBackgroundThread) await BackgroundThread;
}
}
19
View Source File : InputRecordingService.cs
License : Apache License 2.0
Project Creator : abist-co-ltd
License : Apache License 2.0
Project Creator : abist-co-ltd
public string SaveInputAnimation(string filename, string directory = null)
{
if (IsEnabled)
{
string path = Path.Combine(directory ?? Application.persistentDataPath, filename);
try
{
using (Stream fileStream = File.Open(path, FileMode.Create))
{
PruneBuffer();
recordingBuffer.ToStream(fileStream, StartTime);
Debug.Log($"Recorded input animation exported to {path}");
}
return path;
}
catch (IOException ex)
{
Debug.LogWarning(ex.Message);
}
}
return "";
}
19
View Source File : FileCacheTest.cs
License : Apache License 2.0
Project Creator : acarteas
License : Apache License 2.0
Project Creator : acarteas
[TestMethod]
public void AccessTimeoutTest()
{
//AC: This test preplacedes in debug mode, but not in rutime mode. Why?
_cache = new FileCache();
_cache.AccessTimeout = new TimeSpan(1);
_cache["primer"] = 0;
string filePath = Path.Combine(_cache.CacheDir, "cache", "foo.dat");
FileStream stream = File.Open(filePath, FileMode.Create);
try
{
object result = _cache["foo"];
//file access should fail. If it doesn't, the test fails.
true.Should().BeFalse();
}
catch (IOException)
{
//we expect a file exception.
true.Should().BeTrue();
}
stream.Close();
}
19
View Source File : HashedFileCacheTest.cs
License : Apache License 2.0
Project Creator : acarteas
License : Apache License 2.0
Project Creator : acarteas
[TestMethod]
public void AccessTimeoutTest()
{
//AC: This test preplacedes in debug mode, but not in rutime mode. Why?
_cache = new FileCache();
_cache.AccessTimeout = new TimeSpan(1);
_cache["primer"] = 0;
string filePath = Path.Combine(_cache.CacheDir, "cache", HashedFileCacheManager.ComputeHash("primer") + "_0.dat");
FileStream stream = File.Open(filePath, FileMode.Create);
try
{
object result = _cache["primer"];
//file access should fail. If it doesn't, the test fails.
true.Should().BeFalse();
}
catch (IOException)
{
//we expect a file exception.
true.Should().BeTrue();
}
stream.Close();
}
19
View Source File : Texture.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
public void ExportTexture(string directory)
{
if (Length == 0) return;
switch (Format)
{
case SurfacePixelFormat.PFID_CUSTOM_RAW_JPEG:
{
string filename = Path.Combine(directory, Id.ToString("X8") + ".jpg");
using (BinaryWriter writer = new BinaryWriter(File.Open(filename, FileMode.Create)))
{
writer.Write(SourceData);
}
}
break;
default:
{
var bitmapImage = GetBitmap();
string filename = Path.Combine(directory, Id.ToString("X8") + ".png");
bitmapImage.Save(filename, ImageFormat.Png);
}
break;
}
}
19
View Source File : Extensions.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static FileStream Open(this RetryPolicy retryPolicy, string path, FileMode mode)
{
return retryPolicy.ExecuteAction(() => File.Open(path, mode));
}
19
View Source File : VlcUtil.cs
License : GNU General Public License v3.0
Project Creator : aduskin
License : GNU General Public License v3.0
Project Creator : aduskin
public static void ScreenshotWithWatermark(string filePath, string watermark, Brush foreground, FontWeight fontWeight, int rows = 3, int columns = 3
, double fontSize = 36, double opacity = 0.3, double angle = -20)
{
BitmapImage bgImage;
//从流中读取图片,防止出现资源被占用的问题
using (BinaryReader reader = new BinaryReader(File.Open(filePath, FileMode.Open)))
{
FileInfo fi = new FileInfo(filePath);
byte[] bytes = reader.ReadBytes((int)fi.Length);
bgImage = new BitmapImage();
bgImage.BeginInit();
bgImage.StreamSource = new MemoryStream(bytes);
bgImage.EndInit();
bgImage.CacheOption = BitmapCacheOption.OnLoad;
}
RenderTargetBitmap composeImage = new RenderTargetBitmap(bgImage.PixelWidth, bgImage.PixelHeight, bgImage.DpiX, bgImage.DpiY, PixelFormats.Default);
fontSize = GetFontSizeByPixel(bgImage.PixelHeight, fontSize);
//设置水印文字效果:字体、颜色等
#if NETCOREAPP
FormattedText signatureTxt = new FormattedText(watermark, CultureInfo.CurrentCulture, FlowDirection.LeftToRight
, new Typeface(SystemFonts.MessageFontFamily, FontStyles.Normal, fontWeight, FontStretches.Normal), fontSize, foreground,
VisualTreeHelper.GetDpi(Application.Current.MainWindow).PixelsPerDip);
#else
FormattedText signatureTxt = new FormattedText(watermark, CultureInfo.CurrentCulture, FlowDirection.LeftToRight
, new Typeface(SystemFonts.MessageFontFamily, FontStyles.Normal, fontWeight, FontStretches.Normal), fontSize, foreground);
#endif
DrawingVisual drawingVisual = new DrawingVisual();
DrawingContext drawingContext = drawingVisual.RenderOpen();
drawingContext.DrawImage(bgImage, new Rect(0, 0, bgImage.Width, bgImage.Height));
#region 设置水印的旋转角度及透明度,需要在绘制水印文本之前设置,否则不生效
//x,y为水印旋转的中心点
double centerX = (bgImage.Width - signatureTxt.Width) / 2;
double centerY = (bgImage.Height - signatureTxt.Height) / 2;
//设置水印透明度
drawingContext.PushOpacity(opacity);
//设置水印旋转角度
drawingContext.PushTransform(new RotateTransform(angle, centerX, centerY));
#endregion
#region 绘制全屏水印
double intervalX = bgImage.Width / columns; //水印水平间隔
double intervalY = bgImage.Height / rows; //水印垂直间隔
//水印绘制方向:从上往下,再从左到右
for (double i = 0; i < bgImage.Width; i += intervalX)
{
for (double j = 0; j < bgImage.Height + intervalY; j += intervalY)
{
//奇偶行间隔绘制水印
if ((j / intervalY) % 2 == 0)
{
drawingContext.DrawText(signatureTxt, new Point(i, j));
}
else
{
drawingContext.DrawText(signatureTxt, new Point(i + intervalX / 2, j));
}
}
}
#endregion
drawingContext.Close();
composeImage.Render(drawingVisual);
PngBitmapEncoder bitmapEncoder = new PngBitmapEncoder();
bitmapEncoder.Frames.Add(BitmapFrame.Create(composeImage));
//删除VLC生成的原始截图
File.Delete(filePath);
//将合成水印的截图保存到本地
using (Stream stream = File.OpenWrite(filePath))
{
bitmapEncoder.Save(stream);
}
bgImage = null;
}
19
View Source File : ModEntry.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn
License : GNU General Public License v3.0
Project Creator : aedenthorn
public override void Entry(IModHelper helper)
{
context = this;
Config = Helper.ReadConfig<ModConfig>();
if (!Config.EnableMod)
return;
helper.Events.GameLoop.GameLaunched += GameLoop_GameLaunched;
helper.Events.GameLoop.DayStarted += GameLoop_DayStarted;
helper.Events.Player.Warped += Player_Warped;
var harmony = HarmonyInstance.Create(ModManifest.UniqueID);
harmony.Patch(
original: AccessTools.Method(typeof(Object), nameof(Object.placementAction)),
postfix: new HarmonyMethod(typeof(ModEntry), nameof(placementAction_Postfix))
);
harmony.Patch(
original: AccessTools.Method(typeof(Object), nameof(Object.performRemoveAction)),
postfix: new HarmonyMethod(typeof(ModEntry), nameof(performRemoveAction_Postfix))
);
harmony.Patch(
original: AccessTools.Method(typeof(Object), nameof(Object.checkForAction)),
prefix: new HarmonyMethod(typeof(ModEntry), nameof(checkForAction_Prefix))
);
harmony.Patch(
original: AccessTools.Method(typeof(Object), nameof(Object.isPreplacedable)),
prefix: new HarmonyMethod(typeof(ModEntry), nameof(Object_isPreplacedable_Prefix))
);
if (Config.LoadCustomTerrarium)
{
try
{
string path = Directory.GetParent(helper.DirectoryPath).GetDirectories().Where(f => f.FullName.EndsWith("[CP] Lively Frog Sanctuary")).FirstOrDefault()?.FullName;
if (path != null)
{
Texture2D tex = new Texture2D(Game1.graphics.GraphicsDevice, 48, 48);
Color[] data = new Color[tex.Width * tex.Height];
tex.GetData(data);
FileStream setStream = File.Open(Path.Combine(path, "replacedets", "frog-vivarium.png"), FileMode.Open);
Texture2D source = Texture2D.FromStream(Game1.graphics.GraphicsDevice, setStream);
setStream.Dispose();
Color[] srcData = new Color[source.Width * source.Height];
source.GetData(srcData);
for (int i = 0; i < srcData.Length; i++)
{
if (data.Length <= i + 48 * 12)
break;
data[i + 48 * 12] = srcData[i];
}
tex.SetData(data);
string outDir = Directory.GetParent(helper.DirectoryPath).GetDirectories().Where(f => f.FullName.EndsWith("[BC] Terrarium")).FirstOrDefault()?.FullName;
Stream stream = File.Create(Path.Combine(outDir, "replacedets", "terrarium.png"));
tex.SaveAsPng(stream, tex.Width, tex.Height);
stream.Dispose();
Monitor.Log("Terrarium overwritten with lively frog sanctuary", LogLevel.Debug);
}
}
catch (Exception ex)
{
Monitor.Log($"Can't load lively frog sanctuary for Terrarium\n{ex}", LogLevel.Error);
}
}
}
19
View Source File : MainViewModel.cs
License : MIT License
Project Creator : ahopper
License : MIT License
Project Creator : ahopper
void loadAllIcons()
{
foreach (var path in Directory.EnumerateFiles("Icons", "*.xaml"))
{
using (var stream = File.Open(path, FileMode.Open))
{
loadIcons(stream, Icons);
}
}
}
19
View Source File : PackageDownloadsJsonSource.cs
License : MIT License
Project Creator : ai-traders
License : MIT License
Project Creator : ai-traders
private async Task<Stream> GetDownloadsStreamAsync()
{
_logger.LogInformation("Downloading downloads.v1.json...");
var fileStream = File.Open(Path.GetTempFileName(), FileMode.Create);
var response = await _httpClient.GetAsync(PackageDownloadsV1Url, HttpCompletionOption.ResponseHeadersRead);
response.EnsureSuccessStatusCode();
using (var networkStream = await response.Content.ReadreplacedtreamAsync())
{
await networkStream.CopyToAsync(fileStream);
}
fileStream.Seek(0, SeekOrigin.Begin);
_logger.LogInformation("Downloaded downloads.v1.json");
return fileStream;
}
19
View Source File : FilePackageStorageService.cs
License : MIT License
Project Creator : ai-traders
License : MIT License
Project Creator : ai-traders
private async Task SaveFileStreamAsync(
string lowercasedId,
string lowercasedNormalizedVersion,
Func<string, string, string> pathFunc,
Stream content,
CancellationToken cancellationToken)
{
var path = pathFunc(lowercasedId, lowercasedNormalizedVersion);
// TODO: Uploads should be idempotent. This should fail if and only if the blob
// already exists but has different content.
using (var fileStream = File.Open(path, FileMode.CreateNew))
{
await content.CopyToAsync(fileStream, DefaultCopyBufferSize, cancellationToken);
}
}
19
View Source File : Embedder.cs
License : MIT License
Project Creator : alexanderkyte
License : MIT License
Project Creator : alexanderkyte
public static WebreplacedemblyEmbedder
FromFile (string inputPath)
{
using (var source = File.Open (inputPath, FileMode.Open)) {
return new WebreplacedemblyEmbedder (source);
}
}
19
View Source File : Environment.cs
License : Apache License 2.0
Project Creator : Algoryx
License : Apache License 2.0
Project Creator : Algoryx
public static bool CanWriteToExisting( string filename )
{
if ( !File.Exists( filename ) )
return false;
var canWrite = false;
using ( var fs = File.Open( filename, FileMode.Open ) )
canWrite = fs.CanWrite;
return canWrite;
}
19
View Source File : DataMockSI.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn
public Task<object> GetFormData(Guid instanceGuid, Type type, string org, string app, int instanceOwnerId, Guid dataId)
{
string dataPath = GetDataBlobPath(org, app, instanceOwnerId, instanceGuid, dataId);
XmlSerializer serializer = new XmlSerializer(type);
try
{
using FileStream sourceStream = File.Open(dataPath, FileMode.OpenOrCreate);
return Task.FromResult(serializer.Deserialize(sourceStream));
}
catch
{
return Task.FromResult(Activator.CreateInstance(type));
}
}
19
View Source File : Visualization.cs
License : MIT License
Project Creator : AmigoCap
License : MIT License
Project Creator : AmigoCap
bool LoadFromFile() {
Tools.StartClock();
ControlPanel.JsonData data = ControlPanel.Instance.data;
int n_of_bytes_per_atom = 0; //number of bytes that atom attributes take per atom
int n_of_atomAttributes = data.atomAttributes.Length;
int n_of_pathAttributes = data.pathAttributes.Length;
for (int i = 0; i < n_of_atomAttributes; i++) {
if (data.atomAttributes[i].type == ControlPanel.JsonData.DataType.float32 || data.atomAttributes[i].type == ControlPanel.JsonData.DataType.int32)
n_of_bytes_per_atom += 4;
else
n_of_bytes_per_atom += 8;
}
float AllTimeMinimumOfColorAttribute = float.PositiveInfinity;
float AllTimeMaximumOfColorAttribute = float.NegativeInfinity;
float ReadAttribute_f(BinaryReader reader, ControlPanel.JsonData.DataType type) {
switch (type) {
case ControlPanel.JsonData.DataType.float32:
return reader.ReadSingle();
case ControlPanel.JsonData.DataType.float64:
return (float)reader.ReadDouble();
case ControlPanel.JsonData.DataType.int32:
return (float)reader.ReadInt32();
case ControlPanel.JsonData.DataType.int64:
return (float)reader.ReadInt64();
default: //Never happens.
return 0f;
}
}
int ReadAttribute_i(BinaryReader reader, ControlPanel.JsonData.DataType type) {
switch (type) {
case ControlPanel.JsonData.DataType.float32:
return (int)reader.ReadSingle();
case ControlPanel.JsonData.DataType.float64:
return (int)reader.ReadDouble();
case ControlPanel.JsonData.DataType.int32:
return reader.ReadInt32();
case ControlPanel.JsonData.DataType.int64:
return (int)reader.ReadInt64();
default: //Never happens.
return 0;
}
}
int N_RoleIndex = -1, ID_RoleIndex = -1;
for (int i = 0; i < n_of_pathAttributes; i++) {
var attr = data.pathAttributes[i];
if (attr.name == data.pathAttributeUsedAs_n_atoms) {
N_RoleIndex = i;
}
if (attr.name == data.pathAttributeUsedAs_id) {
ID_RoleIndex = i;
}
}
float[] atomAttributeValuesBuffer = new float[n_of_atomAttributes];
int X_RoleIndex = -1, Y_RoleIndex = -1, Z_RoleIndex = -1, T_RoleIndex = -1, Color_RoleIndex = -1;
for (int i = 0; i < n_of_atomAttributes; i++) {
var attr = data.atomAttributes[i];
if (attr.name == data.atomAttributeUsedAs_x) {
X_RoleIndex = i;
}
if (attr.name == data.atomAttributeUsedAs_y) {
Y_RoleIndex = i;
}
if (attr.name == data.atomAttributeUsedAs_z) {
Z_RoleIndex = i;
}
if (attr.name == data.atomAttributeUsedAs_t) {
T_RoleIndex = i;
}
if (attr.name == data.atomAttributeUsedAs_color) {
Color_RoleIndex = i;
}
}
//Conversions done here instead of being done everytime for the same value for each atom
Color32 startColor = Color.blue;
Color32 endColor = Color.red;
if (Color_RoleIndex != -1) {
startColor = ControlPanel.LDColor_to_Color(data.atomAttributes[Color_RoleIndex].colorStart);
endColor = ControlPanel.LDColor_to_Color(data.atomAttributes[Color_RoleIndex].colorEnd);
}
Vector3 lowerTruncature = ControlPanel.LDVector3_to_Vector3(data.lowerTruncature);
Vector3 upperTruncature = ControlPanel.LDVector3_to_Vector3(data.upperTruncature);
if (data.useGPSCoords)
Tools.SetGPSOrigin(ControlPanel.LDVector2_to_Vector2(data.GPSOrigin));
bool randomPaths = data.randomPaths;
int chosen_n_paths = data.chosen_n_paths;
int chosen_paths_start = data.chosen_paths_start;
int chosen_paths_end = data.chosen_paths_end;
int chosen_paths_step = data.chosen_paths_step;
if (data.allPaths) {
randomPaths = false;
chosen_n_paths = data.dataset_n_paths;
chosen_paths_start = 0;
chosen_paths_end = data.dataset_n_paths;
chosen_paths_step = 1;
}
int[] keptPaths;
if (data.randomPaths) {
keptPaths = new int[chosen_n_paths];
}
else {
keptPaths = new int[(chosen_paths_end - chosen_paths_start) / chosen_paths_step];
}
if (data.randomPaths) {
SortedSet<int> chosenRandomPaths = new SortedSet<int>(); // SortedSet because keptPaths should always be sorted
System.Random rnd = new System.Random();
for (int i = 0; i < keptPaths.Length; i++) {
while (!chosenRandomPaths.Add(rnd.Next(chosen_paths_start, chosen_paths_end))) { }
}
chosenRandomPaths.CopyTo(keptPaths);
}
else {
for (int i = 0; i < keptPaths.Length; i++) {
keptPaths[i] = chosen_paths_start + i * chosen_paths_step;
}
}
paths = new List<Path>(keptPaths.Length);
Color32[] randomPathColors = new Color32[keptPaths.Length];
for (int i = 0; i < keptPaths.Length; i++)
randomPathColors[i] = UnityEngine.Random.ColorHSV();
Tools.AddClockStop("Generated paths array");
// Load replacedets Bundles
int n_of_replacedetBundles = data.replacedetBundles.Length;
for (int i = 0; i < n_of_replacedetBundles; i++) {
replacedetBundle ab = replacedetBundle.LoadFromFile(Tools.GetFullPath(data.replacedetBundles[i].filename));
if (ab == null) {
Debug.LogWarning("Failed to load replacedetBundle " + data.replacedetBundles[i].name);
continue;
}
GameObject[] prefabs = ab.LoadAllreplacedets<GameObject>();
foreach (GameObject prefab in prefabs) {
if (data.replacedetBundles[i].overrideBundleTransform) {
prefab.transform.position = ControlPanel.LDVector3_to_Vector3(data.replacedetBundles[i].position);
prefab.transform.eulerAngles = ControlPanel.LDVector3_to_Vector3(data.replacedetBundles[i].rotation);
prefab.transform.localScale = ControlPanel.LDVector3_to_Vector3(data.replacedetBundles[i].scale);
}
GameObject go = Instantiate(prefab);
go.transform.SetParent(this.transform, true);
}
ab.Unload(false);
}
Tools.AddClockStop("Loaded replacedetBundles");
string GetCompositeFilename(string filenameBase, string firstSuffix, int fileNumber) {
if (fileNumber == 0)
return filenameBase + firstSuffix;
int firstNumber = int.Parse(firstSuffix);
fileNumber += firstNumber;
string suffix = fileNumber.ToString();
while (suffix.Length < firstSuffix.Length)
suffix = '0' + suffix;
return filenameBase + suffix;
}
int chosen_instants_start = data.chosen_instants_start;
int chosen_instants_end = data.chosen_instants_end;
int chosen_instants_step = data.chosen_instants_step;
if (data.allInstants) {
chosen_instants_start = 0;
chosen_instants_end = data.dataset_n_instants;
chosen_instants_step = 1;
}
int fileStart = 0;
int fileEnd = 1;
if (data.severalFiles_splitInstants) {
fileStart = chosen_instants_start / data.splitInstants_instantsPerFile;
fileEnd = (chosen_instants_end - 1) / data.splitInstants_instantsPerFile + 1;
}
BinaryReader br = null;
for (int i_file = fileStart; i_file < fileEnd; i_file++) {
string currentFileName;
if (data.severalFiles_splitInstants) {
currentFileName = Tools.GetFullPath(GetCompositeFilename(data.filename, data.severalFiles_firstFileSuffix, i_file));
}
else {
currentFileName = Tools.GetFullPath(data.filename);
}
if (br != null)
br.Close();
try {
if (data.endianness == ControlPanel.JsonData.Endianness.big) {
br = new BinaryReader_BigEndian(File.Open(currentFileName, FileMode.Open));
}
else {
br = new BinaryReader(File.Open(currentFileName, FileMode.Open));
}
}
catch (Exception e) {
Debug.LogError("Couldn't load file " + currentFileName + "\n\n" + e.Message);
break;
}
Tools.AddClockStop("Loaded data file " + currentFileName);
int currentPath = 0;
for (int i_path = 0; i_path < keptPaths.Length; i_path++) {
if (br.BaseStream.Position >= br.BaseStream.Length) {
Debug.LogError("Reached EoF on loading paths after " + paths.Count + " paths");
break;
}
int readableInstants = 0;
int pathID = 0;
void ReadPathAttributes() {
//Default values
readableInstants = data.severalFiles_splitInstants ? data.splitInstants_instantsPerFile : data.dataset_n_instants;
pathID = keptPaths[i_path];
for (int j = 0; j < n_of_pathAttributes; j++) {
if (j == N_RoleIndex || j == ID_RoleIndex) {
int attributeValue = ReadAttribute_i(br, data.pathAttributes[j].type);
if (j == N_RoleIndex)
readableInstants = attributeValue;
if (j == ID_RoleIndex)
pathID = attributeValue;
}
else {
ReadAttribute_f(br, data.pathAttributes[j].type);
}
}
}
ReadPathAttributes();
while (currentPath < keptPaths[i_path]) {
br.BaseStream.Position += readableInstants * n_of_bytes_per_atom;
ReadPathAttributes();
currentPath++;
}
Path p;
if (i_file == fileStart) {
GameObject go;
go = new GameObject(pathID.ToString());
go.transform.parent = transform;
p = go.AddComponent<Path>();
p.atoms = new List<Atom>();
if (!data.severalFiles_splitInstants)
p.atoms.Capacity = Math.Min((chosen_instants_end - chosen_instants_start) / chosen_instants_step, (readableInstants - chosen_instants_start) / chosen_instants_step);
paths.Add(p);
}
else {
p = paths[i_path];
}
long nextPathPosition = br.BaseStream.Position + readableInstants * n_of_bytes_per_atom;
int localInstant = 0;
if (i_file == fileStart) {
localInstant = chosen_instants_start - i_file * data.splitInstants_instantsPerFile;
br.BaseStream.Position += localInstant * n_of_bytes_per_atom;
}
else {
//Handles the following problem:
//Files of 10, step of 4, start at 0: on the second file, should start at localInstant = 2 because 12%4 == 0 (and not 0 because 10%4 != 0)
int preplacededInstantsAtFileStart = i_file * data.splitInstants_instantsPerFile - data.chosen_instants_start;
localInstant = (data.chosen_instants_step - (preplacededInstantsAtFileStart % data.chosen_instants_step)) % data.chosen_instants_step;
br.BaseStream.Position += localInstant * n_of_bytes_per_atom;
}
int lastInstantToRead = readableInstants;
if (i_file == fileEnd - 1) {
lastInstantToRead = Math.Min(lastInstantToRead, chosen_instants_end - i_file * data.splitInstants_instantsPerFile);
}
int atomIndex = p.atoms.Count;
while (localInstant < lastInstantToRead) {
Atom a = new Atom {
path = p,
indexInPath = atomIndex
};
for (int k = 0; k < n_of_atomAttributes; k++) {
atomAttributeValuesBuffer[k] = ReadAttribute_f(br, data.atomAttributes[k].type);
}
if (data.useGPSCoords) {
if (X_RoleIndex != -1 && Z_RoleIndex != -1) {
a.point = Tools.GPSToXYZ(new Vector2(atomAttributeValuesBuffer[X_RoleIndex], atomAttributeValuesBuffer[Z_RoleIndex]));
}
}
else {
if (X_RoleIndex != -1)
a.point.x = atomAttributeValuesBuffer[X_RoleIndex];
if (Z_RoleIndex != -1)
a.point.z = atomAttributeValuesBuffer[Z_RoleIndex];
}
if (Y_RoleIndex != -1)
a.point.y = atomAttributeValuesBuffer[Y_RoleIndex];
a.point.x += data.atomAttributes[X_RoleIndex].positionOffset;
a.point.y += data.atomAttributes[Y_RoleIndex].positionOffset;
a.point.z += data.atomAttributes[Z_RoleIndex].positionOffset;
a.point.x *= data.atomAttributes[X_RoleIndex].sizeCoeff;
a.point.y *= data.atomAttributes[Y_RoleIndex].sizeCoeff;
a.point.z *= data.atomAttributes[Z_RoleIndex].sizeCoeff;
a.point = Vector3.Max(a.point, lowerTruncature);
a.point = Vector3.Min(a.point, upperTruncature);
if (T_RoleIndex != -1)
a.time = atomAttributeValuesBuffer[T_RoleIndex];
else
a.time = i_file * data.splitInstants_instantsPerFile + localInstant;
if (Color_RoleIndex != -1) {
a.colorValue = atomAttributeValuesBuffer[Color_RoleIndex];
if (data.atomAttributes[Color_RoleIndex].valueColorUseMinMax) {
AllTimeMinimumOfColorAttribute = Mathf.Min(AllTimeMinimumOfColorAttribute, a.colorValue);
AllTimeMaximumOfColorAttribute = Mathf.Max(AllTimeMaximumOfColorAttribute, a.colorValue);
}
else {
ControlPanel.JsonData.AtomAttribute attr = data.atomAttributes[Color_RoleIndex];
a.BaseColor = Color32.Lerp(startColor, endColor, (a.colorValue - attr.valueColorStart) / (attr.valueColorEnd - attr.valueColorStart));
}
}
else {
a.BaseColor = randomPathColors[i_path];
}
p.atoms.Add(a);
atomIndex++;
localInstant += chosen_instants_step;
br.BaseStream.Position += (chosen_instants_step - 1) * n_of_bytes_per_atom; //Skip atoms if necessary
}
br.BaseStream.Position = nextPathPosition;
currentPath++;
}
}
if (Color_RoleIndex != -1 && data.atomAttributes[Color_RoleIndex].valueColorUseMinMax) {
for (int j = 0; j < paths.Count; j++) {
for (int i = 0; i < paths[j].atoms.Count; i++) {
Atom a = paths[j].atoms[i];
a.BaseColor = Color32.Lerp(startColor, endColor, (a.colorValue - AllTimeMinimumOfColorAttribute) / (AllTimeMaximumOfColorAttribute - AllTimeMinimumOfColorAttribute));
}
}
}
Tools.EndClock("Loaded paths");
return true;
}
19
View Source File : UwpProjectPostProcess.cs
License : MIT License
Project Creator : anderm
License : MIT License
Project Creator : anderm
private static void WriteXmlDoreplacedentToFile(XmlDoreplacedent doreplacedent, string fullPath)
{
FileStream fileStream = null;
try
{
fileStream = File.Open(fullPath, FileMode.Create);
var settings = new XmlWriterSettings
{
Indent = true,
CloseOutput = true
};
using (XmlWriter writer = XmlWriter.Create(fileStream, settings))
{
fileStream = null;
doreplacedent.WriteTo(writer);
}
}
finally
{
if (fileStream != null)
{
fileStream.Dispose();
}
}
}
19
View Source File : FileSystemEmergencyCache.cs
License : MIT License
Project Creator : andyalm
License : MIT License
Project Creator : andyalm
public void Save(IDictionary<string, string> settings)
{
using (var stream = File.Open(_filePath.Value, FileMode.Create))
{
var writer = new JsonTextWriter(new StreamWriter(stream));
_jsonSerializer.Serialize(writer, settings);
writer.Flush();
}
}
19
View Source File : TemplateProcessor.cs
License : MIT License
Project Creator : andyalm
License : MIT License
Project Creator : andyalm
private TextWriter OpenOutput()
{
if (OutputPath == null || OutputPath.Equals("STDOUT"))
{
return Console.Out;
}
return new StreamWriter(File.Open(OutputPath, FileMode.Create));
}
19
View Source File : BaseFileManager.cs
License : MIT License
Project Creator : angelsix
License : MIT License
Project Creator : angelsix
public async Task WriteTextToFileAsync(string text, string path, bool append = false)
{
// TODO: Add exception catching
// Normalize path
path = NormalizePath(path);
// Resolve to absolute path
path = ResolvePath(path);
// Lock the task
await AsyncAwaiter.AwaitAsync(nameof(BaseFileManager) + path, async () =>
{
// Run the synchronous file access as a new task
await TaskManager.Run(() =>
{
// Write the log message to file
using (var fileStream = (TextWriter)new StreamWriter(File.Open(path, append ? FileMode.Append : FileMode.Create)))
fileStream.Write(text);
});
});
}
19
View Source File : RequestBot.cs
License : GNU Lesser General Public License v3.0
Project Creator : angturil
License : GNU Lesser General Public License v3.0
Project Creator : angturil
private static async void ProcessSongRequest(int index, bool fromHistory = false)
{
if ((RequestQueue.Songs.Count > 0 && !fromHistory) || (RequestHistory.Songs.Count > 0 && fromHistory))
{
SongRequest request = null;
if (!fromHistory)
{
SetRequestStatus(index, RequestStatus.Played);
request = DequeueRequest(index);
}
else
{
request = RequestHistory.Songs.ElementAt(index);
}
if (request == null)
{
Plugin.Log("Can't process a null request! Aborting!");
return;
}
else
Plugin.Log($"Processing song request {request.song["songName"].Value}");
string songName = request.song["songName"].Value;
string songIndex = $"{request.song["id"].Value} ({request.song["songName"].Value} - {request.song["levelAuthor"].Value})";
songIndex = normalize.RemoveDirectorySymbols(ref songIndex); // Remove invalid characters.
string currentSongDirectory = Path.Combine(Environment.CurrentDirectory, "Beat Saber_Data\\CustomLevels", songIndex);
string songHash = request.song["hash"].Value.ToUpper();
// Check to see if level exists, download if not.
// Replace with level check.
//CustomLevel[] levels = SongLoader.CustomLevels.Where(l => l.levelID.StartsWith(songHash)).ToArray();
//if (levels.Length == 0)
var rat = SongCore.Collections.levelIDsForHash(songHash);
bool mapexists = (rat.Count>0) && (rat[0] != "");
if (!SongCore.Loader.CustomLevels.ContainsKey(currentSongDirectory) && !mapexists)
{
EmptyDirectory(".requestcache", false);
//SongMap map;
//if (MapDatabase.MapLibrary.TryGetValue(songIndex, out map))
//{
// if (map.path != "")
// {
// songIndex = map.song["version"].Value;
// songName = map.song["songName"].Value;
// currentSongDirectory = Path.Combine(Environment.CurrentDirectory, "CustomSongs", songIndex);
// songHash = map.song["hashMd5"].Value.ToUpper();
// Directory.CreateDirectory(currentSongDirectory);
// // HACK to allow playing alternate songs not in custom song directory
// CopyFilesRecursively(new DirectoryInfo(map.path),new DirectoryInfo( currentSongDirectory));
// goto here;
// }
//}
//Plugin.Log("Downloading");
if (Directory.Exists(currentSongDirectory))
{
EmptyDirectory(currentSongDirectory, true);
Plugin.Log($"Deleting {currentSongDirectory}");
}
string localPath = Path.Combine(Environment.CurrentDirectory, ".requestcache", $"{request.song["id"].Value}.zip");
//string dl = $"https://beatsaver.com {request.song["downloadURL"].Value}";
//Instance.QueueChatMessage($"Download url: {dl}, {request.song}");
// Insert code to replace local path with ZIP path here
//SongMap map;
//if (MapDatabase.MapLibrary.TryGetValue(songIndex, out map))
//{
// if (map.path != "")
// {
// songIndex = map.song["version"].Value;
// songName = map.song["songName"].Value;
// currentSongDirectory = Path.Combine(Environment.CurrentDirectory, "CustomSongs", songIndex);
// songHash = map.song["hashMd5"].Value.ToUpper();
// Directory.CreateDirectory(currentSongDirectory);
// // HACK to allow playing alternate songs not in custom song directory
// CopyFilesRecursively(new DirectoryInfo(map.path),new DirectoryInfo( currentSongDirectory));
// goto here;
// }
//}
byte[] songZip = null;
if (!string.IsNullOrEmpty(RequestBotConfig.Instance.offlinepath))
{
// build cache name to check
var cacheName = $"{request.song["id"].Value}_{request.song["hash"].Value}.zip";
Plugin.Log($"{RequestBotConfig.Instance.offlinepath} - {cacheName}");
var cachePath = Path.Combine(RequestBotConfig.Instance.offlinepath, cacheName);
// check if a local cache exists, if so, copy it
if (File.Exists(cachePath))
{
Plugin.Log($"{request.song["id"]} found in offline cache");
using (var stream = File.Open(cachePath, FileMode.Open))
{
songZip = new byte[stream.Length];
await stream.ReadAsync(songZip, 0, (int)stream.Length, System.Threading.CancellationToken.None);
}
}
}
if (songZip == null)
{
#if UNRELEASED
// Direct download hack
var ext = Path.GetExtension(request.song["coverURL"].Value);
var k = request.song["downloadURL"].Value;
songZip = await Plugin.WebClient.DownloadSong($"{k}", System.Threading.CancellationToken.None);
#else
songZip = await Plugin.WebClient.DownloadSong($"https://cdn.beatsaver.com{request.song["downloadURL"].Value}", System.Threading.CancellationToken.None);
#endif
}
Stream zipStream = new MemoryStream(songZip);
try
{
// open zip archive from memory stream
ZipArchive archive = new ZipArchive(zipStream, ZipArchiveMode.Read);
archive.ExtractToDirectory(currentSongDirectory);
archive.Dispose();
}
catch (Exception e)
{
Plugin.Log($"Unable to extract ZIP! Exception: {e}");
return;
}
zipStream.Close();
here:
await Task.Run(async () =>
{
while (!SongCore.Loader.AreSongsLoaded && SongCore.Loader.AreSongsLoading) await Task.Delay(25);
});
Loader.Instance.RefreshSongs();
await Task.Run(async () =>
{
while (!SongCore.Loader.AreSongsLoaded && SongCore.Loader.AreSongsLoading) await Task.Delay(25);
});
EmptyDirectory(".requestcache", true);
//levels = SongLoader.CustomLevels.Where(l => l.levelID.StartsWith(songHash)).ToArray();
}
else
{
//Instance.QueueChatMessage($"Directory exists: {currentSongDirectory}");
Plugin.Log($"Song {songName} already exists!");
}
// Dismiss the song request viewcontroller now
//_songRequestMenu.Dismiss();
_flowCoordinator.Dismiss();
if (true)
{
//Plugin.Log($"Scrolling to level {levels[0].levelID}");
bool success = false;
Dispatcher.RunCoroutine(SongListUtils.ScrollToLevel(request.song["hash"].Value.ToUpper(), (s) => success = s, false));
// Redownload the song if we failed to scroll to it
}
else
{
Plugin.Log("Failed to find new level!");
}
if (!request.song.IsNull && RequestBotConfig.Instance.SendNextSongBeingPlayedtoChat)
{
new DynamicText().AddUser(ref request.requestor).AddSong(request.song).QueueMessage(NextSonglink.ToString()); // Display next song message
}
#if UNRELEASED
if (!request.song.IsNull) // Experimental!
{
//ChatHandler.Send("marker "+ new DynamicText().AddUser(ref request.requestor).AddSong(request.song).Parse("%version% songName%"), true);
}
#endif
}
}
19
View Source File : BinaryWriter.cs
License : The Unlicense
Project Creator : Anirban166
License : The Unlicense
Project Creator : Anirban166
public static void Write()
{
using (BinaryWriter writer = new BinaryWriter(File.Open(fileName, FileMode.Create)))
{
writer.Write(1.250F);
writer.Write(@"c:\Temp");
}
}
19
View Source File : TokenInfoDictionaryCompilerBase.cs
License : Apache License 2.0
Project Creator : AnkiUniversal
License : Apache License 2.0
Project Creator : AnkiUniversal
protected void WriteDictionary(string absoluteFilePath)
{
using (TokenInfoBufferCompiler tokenInfoBufferCompiler = new TokenInfoBufferCompiler(bufferEntries))
using (var fos = File.Open(absoluteFilePath, FileMode.OpenOrCreate))
{
tokenInfoBufferCompiler.Compile(fos);
}
}
19
View Source File : DictionaryCompilerBase.cs
License : Apache License 2.0
Project Creator : AnkiUniversal
License : Apache License 2.0
Project Creator : AnkiUniversal
protected void BuildUnknownWordDictionary(string inputDirAbsolutePath, string outputDirAbsolutePath, string encoding, EncodingProvider provider)
{
try
{
ProgressLog.Begin("compiling unknown word dict");
CharacterDefinitionsCompiler charDefCompiler = new CharacterDefinitionsCompiler(provider);
string outputFilePath = outputDirAbsolutePath + Path.DirectorySeparatorChar + CharacterDefinitions.CHARACTER_DEFINITIONS_FILENAME;
using (var stream = File.OpenRead(inputDirAbsolutePath + Path.DirectorySeparatorChar + "char.def"))
using (var outputStream = File.Open(outputFilePath, FileMode.OpenOrCreate))
{
charDefCompiler.ReadCharacterDefinition(stream, encoding);
charDefCompiler.Compile(outputStream);
}
UnknownDictionaryCompiler unkDefCompiler = new UnknownDictionaryCompiler(charDefCompiler.MakeCharacterCategoryMap());
outputFilePath = outputDirAbsolutePath + Path.DirectorySeparatorChar + UnknownDictionary.UNKNOWN_DICTIONARY_FILENAME;
using (var stream = File.OpenRead(inputDirAbsolutePath + Path.DirectorySeparatorChar + "unk.def"))
using (var outputStream = File.Open(outputFilePath, FileMode.OpenOrCreate))
{
unkDefCompiler.ReadUnknownDefinition(stream, encoding);
unkDefCompiler.Compile(outputStream);
}
ProgressLog.End();
}
catch (Exception ex)
{
throw new Exception("DictionaryCompilerBase.BuildUnknownWordDictionary: " + ex.Message);
}
}
19
View Source File : DictionaryCompilerBase.cs
License : Apache License 2.0
Project Creator : AnkiUniversal
License : Apache License 2.0
Project Creator : AnkiUniversal
private void BuildConnectionCosts(string inputDirAbsolutePath, string outputDirAbsolutePath)
{
try
{
ProgressLog.Begin("compiling connection costs");
string outputFilePath = outputDirAbsolutePath + Path.DirectorySeparatorChar + ConnectionCosts.CONNECTION_COSTS_FILENAME;
using(var inputSream = File.OpenRead(inputDirAbsolutePath + Path.DirectorySeparatorChar + "matrix.def"))
using (var outputStream = File.Open(outputFilePath, FileMode.OpenOrCreate))
{
using (ConnectionCostsCompiler connectionCostsCompiler = new ConnectionCostsCompiler())
{
connectionCostsCompiler.ReadCosts(inputSream);
connectionCostsCompiler.Compile(outputStream);
}
ProgressLog.End();
}
}
catch (Exception ex)
{
throw new Exception("DictionaryCompilerBase.BuildConnectionCosts: " + ex.Message);
}
}
19
View Source File : TokenInfoDictionaryCompilerBase.cs
License : Apache License 2.0
Project Creator : AnkiUniversal
License : Apache License 2.0
Project Creator : AnkiUniversal
protected void WriteMap(string absoluteFilePath, FeatureInfoMap map)
{
SortedDictionary<int, string> features = map.Invert();
using(StringValueMapBuffer mapBuffer = new StringValueMapBuffer(features))
using(var fos = File.Open(absoluteFilePath, FileMode.OpenOrCreate))
{
mapBuffer.Write(fos);
}
}
19
View Source File : TokenInfoDictionaryCompilerBase.cs
License : Apache License 2.0
Project Creator : AnkiUniversal
License : Apache License 2.0
Project Creator : AnkiUniversal
protected void WriteWordIds(string absoluteFilePath)
{
using (var fos = File.Open(absoluteFilePath, FileMode.OpenOrCreate))
{
wordIdsCompiler.Write(fos);
}
}
19
View Source File : FSTFormatter.cs
License : Apache License 2.0
Project Creator : AnkiUniversal
License : Apache License 2.0
Project Creator : AnkiUniversal
public string Format(Builder builder, string outFileAbsoultePath)
{
StringBuilder sb = new StringBuilder();
sb.Append(FormatHeader());
sb.Append(FormatHashedNodes(builder));
sb.Append(FormatTrailer());
try
{
using (var fw = File.Open(outFileAbsoultePath, FileMode.Create))
using (var writer = new StreamWriter(fw))
{
writer.Write(sb.ToString());
}
}
catch (IOException e)
{
Debug.WriteLine(e.Message);
}
return "";
}
19
View Source File : UserDictionaryTokenizerTest.cs
License : Apache License 2.0
Project Creator : AnkiUniversal
License : Apache License 2.0
Project Creator : AnkiUniversal
[TestMethod]
public void TestTsunk()
{
string userDictionary = "" +
"シャ乱Q つんく♂,シャ乱Q つんく ♂,シャランキュー ツンク ボーイ,カスタムアーティスト名";
using (Tokenizer tokenizer = MakeTokenizer(userDictionary))
{
using (var output = File.Open("./tsunk.gv", FileMode.Create))
{
tokenizer.DebugTokenize(output, "シャQ");
}
}
}
19
View Source File : WordFileUtils.cs
License : GNU Lesser General Public License v3.0
Project Creator : antonmihaylov
License : GNU Lesser General Public License v3.0
Project Creator : antonmihaylov
public static WordprocessingDoreplacedent OpenFile(string path, OpenSettings openSettings)
{
if (string.IsNullOrEmpty(path))
throw new ArgumentNullException(nameof(path));
var ext = Path.GetExtension(path);
if (ext != ".doc" && ext != ".docx")
throw new FileFormatException(new Uri(path), "The supported formats are .doc and .docx");
//Read the file and write it to a stream.
using var stream = File.Open(path, FileMode.Open);
//Let's not risk corrupting the original file and feed the doreplacedent a memorystream instead
var memoryStream = new MemoryStream();
stream.CopyTo(memoryStream);
// The WordprocessingDoreplacedent should dispose the stream. (I hope)
return WordprocessingDoreplacedent.Open(memoryStream, true, openSettings);
}
19
View Source File : SaveWidget.cs
License : GNU General Public License v3.0
Project Creator : AnyStatus
License : GNU General Public License v3.0
Project Creator : AnyStatus
public async Task<bool> Handle(Request request, CancellationToken cancellationToken)
{
var directory = Path.GetDirectoryName(request.FileName);
if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
var json = JsonConvert.SerializeObject(request.Widget, Formatting.Indented, new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All,
PreserveReferencesHandling = PreserveReferencesHandling.Objects
});
var bytes = new UTF8Encoding().GetBytes(json);
using (var stream = File.Open(request.FileName, FileMode.Create))
{
stream.Seek(0, SeekOrigin.End);
await stream.WriteAsync(bytes, 0, bytes.Length, cancellationToken).ConfigureAwait(false);
}
return true;
}
19
View Source File : MdDocument.cs
License : MIT License
Project Creator : ap0llo
License : MIT License
Project Creator : ap0llo
public void Save(string path, MdSerializationOptions? serializationOptions)
{
using (var stream = File.Open(path, FileMode.Create))
{
Save(stream, serializationOptions);
}
}
19
View Source File : CommentsTest.cs
License : Apache License 2.0
Project Creator : Appdynamics
License : Apache License 2.0
Project Creator : Appdynamics
[TestMethod]
public void VisibilityComments()
{
var xlsxName = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xlsx");
try
{
using (var ms = File.Open(xlsxName, FileMode.OpenOrCreate))
using (var pkg = new ExcelPackage(ms))
{
var ws = pkg.Workbook.Worksheets.Add("Comment");
var a1 = ws.Cells["A1"];
a1.Value = "Justin Dearing";
a1.AddComment("I am A1s comment", "JD");
replacedert.IsFalse(a1.Comment.Visible); // Comments are by default invisible
a1.Comment.Visible = true;
a1.Comment.Visible = false;
replacedert.IsNotNull(a1.Comment);
//check style attribute
var stylesDict = new System.Collections.Generic.Dictionary<string, string>();
string[] styles = a1.Comment.Style
.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
foreach(var s in styles)
{
string[] split = s.Split(':');
if (split.Length == 2)
{
var k = (split[0] ?? "").Trim().ToLower();
var v = (split[1] ?? "").Trim().ToLower();
stylesDict[k] = v;
}
}
replacedert.IsTrue(stylesDict.ContainsKey("visibility"));
//replacedert.AreEqual("visible", stylesDict["visibility"]);
replacedert.AreEqual("hidden", stylesDict["visibility"]);
replacedert.IsFalse(a1.Comment.Visible);
pkg.Save();
ms.Close();
}
}
finally
{
//open results file in program for view xlsx.
//comments of cell A1 must be hidden.
//System.Diagnostics.Process.Start(Path.GetDirectoryName(xlsxName));
File.Delete(xlsxName);
}
}
19
View Source File : Issues.cs
License : Apache License 2.0
Project Creator : Appdynamics
License : Apache License 2.0
Project Creator : Appdynamics
[TestMethod, Ignore]
public void Issue99()
{
var template = @"c:\temp\bug\iss99\Template.xlsx";
var result = @"c:\temp\bug\iss99\Result.xlsx";
using (var inStream = File.Open(template, FileMode.Open))
{
using (var outStream = File.Open(result, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
using (ExcelPackage xl = new ExcelPackage(outStream, inStream))
{
xl.Save();
}
}
}
}
19
View Source File : Program.cs
License : MIT License
Project Creator : Arefu
License : MIT License
Project Creator : Arefu
[STAThread]
private static void Main(string[] Args)
{
var UseArgs = false;
var TocFileLocation = "";
if (Args.Length > 0)
{
TocFileLocation = Args.FirstOrDefault(File.Exists);
if (TocFileLocation != null)
UseArgs = true;
else
Utilities.Log("Coun't Find TOC File.", Utilities.Event.Warning);
}
Console.replacedle = "Onomatopaira";
using (var FileDialog = new OpenFileDialog())
{
FileDialog.replacedle = "Open Yu-Gi-Oh TOC File...";
FileDialog.Filter = "Yu-Gi-Oh! Wolf TOC File |*.toc";
if (UseArgs == false)
{
if (FileDialog.ShowDialog() != DialogResult.OK) return;
TocFileLocation = FileDialog.FileName;
}
try
{
using (var reader = new StreamReader(TocFileLocation))
{
if (!File.Exists(TocFileLocation.Replace(".toc", ".dat")))
Utilities.Log("Can't Find DAT File.", Utilities.Event.Error, true, 1);
var datReader =
new BinaryReader(File.Open(TocFileLocation.Replace(".toc", ".dat"), FileMode.Open));
reader.ReadLine();
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
if (line == null) continue;
line = line.TrimStart(' ');
line = Regex.Replace(line, @" +", " ", RegexOptions.Compiled);
var Data = new FileInformation(line.Split(new char[] { ' ' }, 3));
Utilities.Log(
$"Extracting File: {new FileInfo(Data.FileName).Name} ({Data.FileSize} Bytes)",
Utilities.Event.Information);
new FileInfo("YGO_DATA/" + Data.FileName).Directory?.Create();
var ExtraBytes = Utilities.HexToDec(Data.FileSize);
if (Utilities.HexToDec(Data.FileSize) % 4 != 0)
while (ExtraBytes % 4 != 0)
ExtraBytes = ExtraBytes + 1;
using (var FileWriter = new BinaryWriter(File.Open("YGO_DATA/" + Data.FileName,
FileMode.Create, FileAccess.Write)))
{
FileWriter.Write(datReader.ReadBytes(Utilities.HexToDec(Data.FileSize)));
FileWriter.Flush();
}
datReader.BaseStream.Position += ExtraBytes - Utilities.HexToDec(Data.FileSize);
}
}
}
catch (Exception Ex)
{
Utilities.Log($"Exception Caught: {Ex.Message}", Utilities.Event.Error, true, 1);
}
}
}
19
View Source File : MinerProgramBase.cs
License : GNU General Public License v3.0
Project Creator : arunsatyarth
License : GNU General Public License v3.0
Project Creator : arunsatyarth
public virtual void SaveToBAtFile()
{
try
{
FileStream stream = File.Open(BATFILE, FileMode.Create);
StreamWriter sw = new StreamWriter(stream);
sw.Write(Script);
sw.Flush();
sw.Close();
//generate script and write to folder
}
catch (Exception e)
{
}
}
19
View Source File : MinerProgramBase.cs
License : GNU General Public License v3.0
Project Creator : arunsatyarth
License : GNU General Public License v3.0
Project Creator : 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
View Source File : EsmFileReader.cs
License : GNU General Public License v3.0
Project Creator : arycama
License : GNU General Public License v3.0
Project Creator : arycama
private void Awake()
{
var fileStream = File.Open(path, FileMode.Open);
reader = new System.IO.BinaryReader(fileStream);
while (reader.BaseStream.Position < reader.BaseStream.Length)
Record.Create(reader);
}
19
View Source File : RealFileWriter.cs
License : GNU General Public License v3.0
Project Creator : asimmon
License : GNU General Public License v3.0
Project Creator : asimmon
public async Task SaveScreenshot(string path, byte[] screenshotBytes)
{
#if NETSTANDARD2_0
using (var fileStream = File.Open(path, FileMode.Create))
{
await fileStream.WriteAsync(screenshotBytes, 0, screenshotBytes.Length).ConfigureAwait(false);
}
#else
await using (var fileStream = File.Open(path, FileMode.Create))
{
await fileStream.WriteAsync(screenshotBytes).ConfigureAwait(false);
}
#endif
}
19
View Source File : JustifyText.cs
License : MIT License
Project Creator : aspose-pdf
License : MIT License
Project Creator : aspose-pdf
public static void Run()
{
// ExStart:JustifyText
// The path to the doreplacedents directory.
string dataDir = RunExamples.GetDataDir_AsposePdfFacades_TechnicalArticles();
using (FileStream source = File.Open(dataDir + "Input1.pdf", FileMode.Open))
{
MemoryStream ms = new MemoryStream();
// Create Form Object
Aspose.Pdf.Facades.Form form = new Aspose.Pdf.Facades.Form();
// Open Source File
form.BindPdf(source);
// Fill Text Field
form.FillField("Text1", "Thank you for using Aspose");
// Save the doreplacedent in Memory Stream
form.Save(ms);
ms.Seek(0, SeekOrigin.Begin);
FileStream dest = new FileStream(dataDir + "JustifyText_out.pdf", FileMode.Create);
// Create formEditor Object
FormEditor formEditor = new FormEditor();
// Open PDF from memory stream
formEditor.BindPdf(ms);
// Set Text Alignment as Justified
formEditor.Facade.Alignment = FormFieldFacade.AlignJustified;
// Decorate form field.
formEditor.DecorateField();
// Save te resultant file.
formEditor.Save(dest);
// Close file stream
dest.Close();
}
// ExEnd:JustifyText
}
19
View Source File : Updater.cs
License : GNU General Public License v3.0
Project Creator : atomex-me
License : GNU General Public License v3.0
Project Creator : atomex-me
async Task CheckForUpdatesAsync()
{
try
{
#region check version
var latestVersion = await VersionProvider.GetLatestVersionAsync();
if (latestVersion == PendingUpdate)
return; // already loaded and ready to install
var currentVersion = ProductProvider.GetInstalledVersion();
if (currentVersion >= latestVersion)
return; // already up to date or newer
#endregion
Log.Warning($"Newer version {latestVersion} found, current version {currentVersion}");
#region load binaries
if (!File.Exists(InstallerPath) ||
!ProductProvider.VerifyPackage(InstallerPath) ||
!ProductProvider.VerifyPackageVersion(InstallerPath, latestVersion))
{
Log.Debug("Load binaries");
if (!Directory.Exists(WorkingDirectory))
Directory.CreateDirectory(WorkingDirectory);
using (var binariesStream = await BinariesProvider.GetLatestBinariesAsync())
using (var fileStream = File.Open(InstallerPath, FileMode.Create))
{
await binariesStream.CopyToAsync(fileStream);
}
}
#endregion
Log.Debug($"Binaries loaded");
#region verify binaries
if (!ProductProvider.VerifyPackage(InstallerPath))
{
Log.Warning($"Loaded binaries are untrusted");
return;
}
if (!ProductProvider.VerifyPackageVersion(InstallerPath, latestVersion))
{
Log.Warning($"Loaded binaries are not the latest version");
return;
}
#endregion
Log.Debug("Binaries verified");
PendingUpdate = latestVersion;
UpdatesReady?.Invoke(this, new ReadyEventArgs(latestVersion, InstallerPath));
}
catch (Exception ex)
{
Log.Error(ex, "Failed to check updates");
}
}
19
View Source File : Program.cs
License : MIT License
Project Creator : audfx
License : MIT License
Project Creator : audfx
public void Flush()
{
if (lines.Count == 0) return;
lock (flushLock)
{
int count = lines.Count;
using (var writer = new StreamWriter(File.Open(m_fileName, FileMode.Append)))
{
for (int i = 0; i < count; i++)
writer.WriteLine(lines[i]);
}
lines.RemoveRange(0, count);
}
}
19
View Source File : CreatePackageTests.cs
License : Apache License 2.0
Project Creator : aws
License : Apache License 2.0
Project Creator : aws
public JObject ReadManifestFromPackage(string packagePath)
{
using (var zipStream = File.Open(packagePath, FileMode.Open))
using (var zipArchive = new ZipArchive(zipStream, ZipArchiveMode.Read))
{
var entry = zipArchive.Entries.FirstOrDefault(x => string.Equals(x.Name, "aws-windows-deployment-manifest.json"));
if (entry == null)
throw new Exception("Failed to find aws-windows-deployment-manifest.json in package bundle");
using (var entryReader = new StreamReader(entry.Open()))
{
return JsonConvert.DeserializeObject(entryReader.ReadToEnd()) as JObject;
}
}
}
19
View Source File : FileDownloader.cs
License : Apache License 2.0
Project Creator : awslabs
License : Apache License 2.0
Project Creator : awslabs
public async Task DownloadFileAsync(string url, string toPath)
{
string path = ConvertFileUrlToPath(url);
using (var streamTo = File.Open(toPath, FileMode.Create))
using (var streamFrom = File.OpenRead(path))
{
await streamFrom.CopyToAsync(streamTo);
}
}
19
View Source File : HttpDownloader.cs
License : Apache License 2.0
Project Creator : awslabs
License : Apache License 2.0
Project Creator : awslabs
public async Task DownloadFileAsync(string url, string toPath)
{
using (var streamTo = File.Open(toPath, FileMode.Create))
using (HttpClient httpClient = new HttpClient())
using (var response = await httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead))
{
response.EnsureSuccessStatusCode();
using (var streamFrom = await response.Content.ReadreplacedtreamAsync())
{
await streamFrom.CopyToAsync(streamTo);
}
}
}
19
View Source File : Skeleton.cs
License : GNU Lesser General Public License v2.1
Project Creator : axiom3d
License : GNU Lesser General Public License v2.1
Project Creator : axiom3d
public void DumpContents(string fileName)
{
var fs = File.Open(fileName, FileMode.Create);
var writer = new StreamWriter(fs);
writer.AutoFlush = true;
writer.WriteLine("-= Debug output of skeleton {0} =-", Name);
writer.WriteLine("");
writer.WriteLine("== Bones ==");
writer.WriteLine("Number of bones: {0}", this.boneList.Count);
var q = new Quaternion();
Real angle = 0;
var axis = new Vector3();
// write each bone out
foreach (var bone in this.boneList.Values)
{
writer.WriteLine("-- Bone {0} --", bone.Handle);
writer.Write("Position: {0}", bone.Position);
q = bone.Orientation;
writer.Write("Rotation: {0}", q);
q.ToAngleAxis(ref angle, ref axis);
writer.Write(" = {0} radians around axis {1}", angle, axis);
writer.WriteLine("");
writer.WriteLine("");
}
writer.WriteLine("== Animations ==");
writer.WriteLine("Number of animations: {0}", this.animationList.Count);
// animations
foreach (var anim in this.animationList.Values)
{
writer.WriteLine("-- Animation '{0}' (length {1}) --", anim.Name, anim.Length);
writer.WriteLine("Number of tracks: {0}", anim.NodeTracks.Count);
// tracks
foreach (var track in anim.NodeTracks.Values)
{
writer.WriteLine(" -- AnimationTrack {0} --", track.Handle);
writer.WriteLine(" Affects bone: {0}", ((Bone)track.TargetNode).Handle);
writer.WriteLine(" Number of keyframes: {0}", track.KeyFrames.Count);
// key frames
var kf = 0;
for (ushort i = 0; i < track.KeyFrames.Count; i++)
{
var keyFrame = track.GetNodeKeyFrame(i);
writer.WriteLine(" -- KeyFrame {0} --", kf++);
writer.Write(" Time index: {0}", keyFrame.Time);
writer.WriteLine(" Translation: {0}", keyFrame.Translate);
q = keyFrame.Rotation;
writer.Write(" Rotation: {0}", q);
q.ToAngleAxis(ref angle, ref axis);
writer.WriteLine(" = {0} radians around axis {1}", angle, axis);
}
}
}
writer.Close();
fs.Close();
}
See More Examples