System.IO.File.ReadAllBytes(string)

Here are the examples of the csharp api System.IO.File.ReadAllBytes(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

3347 Examples 7

19 Source : TriggerTest.cs
with MIT License
from aliyun

[Fact]
        public void TestListTriggers()
        {
            tf.Client.CreateService(new CreateServiceRequest(Service));

            byte[] contents = File.ReadAllBytes(Directory.GetCurrentDirectory() + "/hello.zip");
            var code = new Code(Convert.ToBase64String(contents));
            tf.Client.CreateFunction(new CreateFunctionRequest(Service, Function, "python3", "index.handler", code, "desc"));

            string triggerName = "my-oss-trigger";
            string[] events = { "oss:ObjectCreated:PostObject", "oss:ObjectCreated:PutObject" };
            var ossTriggerConfig = new OSSTriggerConfig(events, "pre", ".zip");


            string sourceArn = string.Format("acs:oss:{0}:{1}:{2}", tf.Region, tf.AccountID, tf.CodeBucket);
            tf.Client.CreateTrigger(new CreateTriggerRequest(Service, Function, triggerName, "oss",
                                     sourceArn, tf.InvocationRole, ossTriggerConfig, "oss trigger desc"));

            this.Triggers.Add(triggerName);

            triggerName = "my-log-trigger";
            SouceConfig source = new SouceConfig(tf.LogStore + "_source");
            LogConfig logConfig = new LogConfig(tf.LogProject, tf.LogStore);
            JobConfig jobConfig = new JobConfig(60, 10);
            var functionParameter = new Dictionary<string, object> { };

            var logTriggerConfig = new LogTriggerConfig(source, jobConfig, functionParameter, logConfig, false);

            sourceArn = string.Format("acs:log:{0}:{1}:project/{2}", tf.Region, tf.AccountID, tf.LogProject);
            tf.Client.CreateTrigger(new CreateTriggerRequest(Service, Function, triggerName, "log",
                                     sourceArn, tf.InvocationRole, logTriggerConfig, "log trigger desc"));

            this.Triggers.Add(triggerName);

            var response = tf.Client.ListTriggers(new ListTriggersRequest(Service, Function));
            Console.WriteLine(response.Content);
            replacedert.Equal(2, response.Data.Triggers.GetLength(0));

            var response2 = tf.Client.ListTriggers(new ListTriggersRequest(Service, Function, 10, "my-log-"));
            Console.WriteLine(response2.Content);
            replacedert.Equal(1, response2.Data.Triggers.GetLength(0));
            replacedert.Equal(triggerName, response2.Data.Triggers[0].TriggerName);
            replacedert.Equal("log trigger desc", response2.Data.Triggers[0].Description);
            replacedert.Equal("log", response2.Data.Triggers[0].TriggerType);
            replacedert.Equal(sourceArn, response2.Data.Triggers[0].SourceArn);
            replacedert.Equal(tf.InvocationRole, response2.Data.Triggers[0].InvocationRole);
            replacedert.Equal(JsonConvert.DeserializeObject<LogTriggerConfig>(response2.Data.Triggers[0].TriggerConfig.ToString()), logTriggerConfig);

        }

19 Source : TriggerTest.cs
with MIT License
from aliyun

[Fact]
        public void TestLogTrigger()
        {
            tf.Client.CreateService(new CreateServiceRequest(Service));

            byte[] contents = File.ReadAllBytes(Directory.GetCurrentDirectory() + "/hello.zip");
            var code = new Code(Convert.ToBase64String(contents));
            tf.Client.CreateFunction(new CreateFunctionRequest(Service, Function, "python3", "index.handler", code, "desc"));

            string triggerName = "my-log-trigger";

            SouceConfig source = new SouceConfig(tf.LogStore + "_source");
            LogConfig logConfig = new LogConfig(tf.LogProject, tf.LogStore);
            JobConfig jobConfig = new JobConfig(60, 10);
            var functionParameter = new Dictionary<string, object> { };

            var logTriggerConfig = new LogTriggerConfig(source, jobConfig, functionParameter, logConfig, false);

            string sourceArn = string.Format("acs:log:{0}:{1}:project/{2}", tf.Region, tf.AccountID, tf.LogProject);
            var response = tf.Client.CreateTrigger(new CreateTriggerRequest(Service, Function, triggerName, "log",
                                     sourceArn, tf.InvocationRole, logTriggerConfig, "log trigger desc"));

            this.Triggers.Add(triggerName);

            replacedert.Equal(triggerName, response.Data.TriggerName);
            replacedert.Equal("log trigger desc", response.Data.Description);
            replacedert.Equal("log", response.Data.TriggerType);
            replacedert.Equal(sourceArn, response.Data.SourceArn);
            replacedert.Equal(tf.InvocationRole, response.Data.InvocationRole);
            replacedert.Equal(JsonConvert.DeserializeObject<LogTriggerConfig>(response.Data.TriggerConfig.ToString()), logTriggerConfig);
        }

19 Source : TriggerTest.cs
with MIT License
from aliyun

[Fact]
        public void TestMNSTopicTrigger()
        {
            var client = tf.Client;
            client.CreateService(new CreateServiceRequest(Service));

            byte[] contents = File.ReadAllBytes(Directory.GetCurrentDirectory() + "/hello.zip");
            var code = new Code(Convert.ToBase64String(contents));
            client.CreateFunction(new CreateFunctionRequest(Service, Function, "python3", "index.handler", code, "desc"));

            string triggerName = "my-mns-trigger";

            var mnsTriggerConfig = new MnsTopicTriggerConfig("JSON", "BACKOFF_RETRY", "");
            string sourceArn = string.Format("acs:mns:{0}:{1}:/topics/testTopic", tf.Region, tf.AccountID);
            var response = client.CreateTrigger(new CreateTriggerRequest(Service, Function, triggerName, "mns_topic",
                                     sourceArn, tf.InvocationRole, mnsTriggerConfig, "mns trigger desc"));

            this.Triggers.Add(triggerName);

            replacedert.Equal(200, response.StatusCode);
            replacedert.Equal(triggerName, response.Data.TriggerName);
            replacedert.Equal("mns trigger desc", response.Data.Description);
            replacedert.Equal("mns_topic", response.Data.TriggerType);
            replacedert.Equal(sourceArn, response.Data.SourceArn);
            replacedert.Equal(tf.InvocationRole, response.Data.InvocationRole);
            replacedert.Equal(JsonConvert.DeserializeObject<MnsTopicTriggerConfig>(response.Data.TriggerConfig.ToString()), mnsTriggerConfig);
        }

19 Source : Program.cs
with MIT License
from aliyun

static void Main(string[] args)
        {
            var fcClient = new FCClient("cn-shanghai", "<your account id>", "<your ak id>", "<your ak secret>");
            var response1 = fcClient.CreateService(new CreateServiceRequest("csharp-service", "create by c# sdk"));
            Console.WriteLine(response1.Content);
            Console.WriteLine(response1.Data.ServiceName + "---" + response1.Data.Description);

            byte[] contents = File.ReadAllBytes(@"/Users/songluo/gitpro/fc-dotnet-sdk/Libraries/samples/hello2.zip");
            var code = new Code(Convert.ToBase64String(contents));
            var response2 = fcClient.CreateFunction(new CreateFunctionRequest("csharp-service", "csharp-function", "python3", "index.handler", code));
            Console.WriteLine(response2.Content);

            byte[] payload = Encoding.UTF8.GetBytes("hello csharp world");
            var response3 = fcClient.InvokeFunction(new InvokeFunctionRequest("csharp-service", "csharp-function", null, payload));
            Console.WriteLine(response3.Content);

            var customHeaders = new Dictionary<string, string> {
                {"x-fc-invocation-type", "Async"}
            };
            var response4 = fcClient.InvokeFunction(new InvokeFunctionRequest("csharp-service", "csharp-function", null, payload, customHeaders));
            Console.WriteLine(response4.StatusCode);

            var response5 = fcClient.CreateTrigger(new CreateTriggerRequest("csharp-service", "csharp-function", "my-http-trigger", "http", "dummy_arn", "",
                                                        new HttpTriggerConfig(HttpAuthType.ANONYMOUS, new HttpMethod[] { HttpMethod.GET, HttpMethod.POST })));
            Console.WriteLine(response5.Content);

            var response6 = fcClient.DeleteTrigger(new DeleteTriggerRequest("csharp-service", "csharp-function", "my-http-trigger"));
            Console.WriteLine(response6.StatusCode);

            var response7 = fcClient.DeleteFunction(new DeleteFunctionRequest("test", "fff2"));
            Console.WriteLine(response7.StatusCode);

            var response8 = fcClient.DeleteService(new DeleteServiceRequest("csharp"));
            Console.WriteLine(response8.StatusCode);
        }

19 Source : TriggerTest.cs
with MIT License
from aliyun

[Fact]
        public void TestTriggerCRUD()
        {

            tf.Client.CreateService(new CreateServiceRequest(Service));
               
            byte[] contents = File.ReadAllBytes(Directory.GetCurrentDirectory() + "/hello.zip");
            var code = new Code(Convert.ToBase64String(contents));
            tf.Client.CreateFunction(new CreateFunctionRequest(Service, Function, "python3", "index.handler", code, "desc"));

            string triggerName = "my-http-trigger";
            var httpTriggerConfig = new HttpTriggerConfig(HttpAuthType.ANONYMOUS, new HttpMethod[] { HttpMethod.GET, HttpMethod.POST });
            var response1 = tf.Client.CreateTrigger(new CreateTriggerRequest(Service, Function, triggerName, "http", "dummy_arn", "", httpTriggerConfig));

            this.Triggers.Add(triggerName);

            replacedert.Equal(triggerName, response1.Data.TriggerName);
            replacedert.Equal("", response1.Data.Description);
            replacedert.Equal("http", response1.Data.TriggerType);
            replacedert.Equal(JsonConvert.DeserializeObject<HttpTriggerConfig>(response1.Data.TriggerConfig.ToString()), httpTriggerConfig);

            var newHttpTriggerConfig = new HttpTriggerConfig(HttpAuthType.ANONYMOUS, new HttpMethod[] { HttpMethod.GET });
            var response2 = tf.Client.UpdateTrigger(new UpdateTriggerRequest(Service, Function, triggerName, newHttpTriggerConfig));
            replacedert.Equal(triggerName, response2.Data.TriggerName);
            replacedert.Equal("", response2.Data.Description);
            replacedert.Equal("http", response2.Data.TriggerType);
            replacedert.Equal(JsonConvert.DeserializeObject<HttpTriggerConfig>(response2.Data.TriggerConfig.ToString()), newHttpTriggerConfig);


            var response3 = tf.Client.GetTrigger(new GetTriggerRequest(Service, Function, triggerName));
            replacedert.Equal(triggerName, response3.Data.TriggerName);
            replacedert.Equal("", response3.Data.Description);
            replacedert.Equal("http", response3.Data.TriggerType);
            replacedert.Equal(JsonConvert.DeserializeObject<HttpTriggerConfig>(response3.Data.TriggerConfig.ToString()), newHttpTriggerConfig);


            var response4 = tf.Client.ListTriggers(new ListTriggersRequest(Service, Function));
            Console.WriteLine(response4.Content);
            replacedert.Equal(1, response4.Data.Triggers.GetLength(0));
            replacedert.Equal(triggerName, response4.Data.Triggers[0].TriggerName);
            replacedert.Equal("", response4.Data.Triggers[0].Description);
            replacedert.Equal("http", response4.Data.Triggers[0].TriggerType);
            replacedert.Equal(JsonConvert.DeserializeObject<HttpTriggerConfig>(response4.Data.Triggers[0].TriggerConfig.ToString()), newHttpTriggerConfig);


            var response5 = tf.Client.DeleteTrigger(new DeleteTriggerRequest(Service, Function, triggerName));
            replacedert.Equal(204, response5.StatusCode);
            this.Triggers.Remove(triggerName);
        }

19 Source : TriggerTest.cs
with MIT License
from aliyun

[Fact]
        public void TestOSSTrigger()
        {
            tf.Client.CreateService(new CreateServiceRequest(Service));

            byte[] contents = File.ReadAllBytes(Directory.GetCurrentDirectory() + "/hello.zip");
            var code = new Code(Convert.ToBase64String(contents));
            tf.Client.CreateFunction(new CreateFunctionRequest(Service, Function, "python3", "index.handler", code, "desc"));

            string triggerName = "my-oss-trigger";
            string[] events = { "oss:ObjectCreated:PostObject", "oss:ObjectCreated:PutObject" };
            var ossTriggerConfig = new OSSTriggerConfig(events, "pre", ".zip");


            string sourceArn = string.Format("acs:oss:{0}:{1}:{2}", tf.Region, tf.AccountID, tf.CodeBucket);
            var response = tf.Client.CreateTrigger(new CreateTriggerRequest(Service, Function, triggerName, "oss",
                                     sourceArn, tf.InvocationRole, ossTriggerConfig, "oss trigger desc"));

            this.Triggers.Add(triggerName);

            replacedert.Equal(triggerName, response.Data.TriggerName);
            replacedert.Equal("oss trigger desc", response.Data.Description);
            replacedert.Equal("oss", response.Data.TriggerType);
            replacedert.Equal(sourceArn, response.Data.SourceArn);
            replacedert.Equal(tf.InvocationRole, response.Data.InvocationRole);
            replacedert.Equal(JsonConvert.DeserializeObject<OSSTriggerConfig>(response.Data.TriggerConfig.ToString()), ossTriggerConfig);

        }

19 Source : TriggerTest.cs
with MIT License
from aliyun

[Fact]
        public void TestTimerTrigger()
        {
            tf.Client.CreateService(new CreateServiceRequest(Service));

            byte[] contents = File.ReadAllBytes(Directory.GetCurrentDirectory() + "/hello.zip");
            var code = new Code(Convert.ToBase64String(contents));
            tf.Client.CreateFunction(new CreateFunctionRequest(Service, Function, "python3", "index.handler", code, "desc"));

            string triggerName = "my-timer-trigger";
            var timerTriggerConfig = new TimeTriggerConfig("@every 5m", "awesome-fc", true);
            var response1 = tf.Client.CreateTrigger(new CreateTriggerRequest(Service, Function, triggerName, "timer", "dummy_arn", "", timerTriggerConfig));

            this.Triggers.Add(triggerName);

            replacedert.Equal(triggerName, response1.Data.TriggerName);
            replacedert.Equal("", response1.Data.Description);
            replacedert.Equal("timer", response1.Data.TriggerType);
            replacedert.Equal(JsonConvert.DeserializeObject<TimeTriggerConfig>(response1.Data.TriggerConfig.ToString()), timerTriggerConfig);
        }

19 Source : TriggerTest.cs
with MIT License
from aliyun

[Fact]
        public void TestCDNEventsTrigger()
        {
            var client = tf.Client;
            client.CreateService(new CreateServiceRequest(Service));

            byte[] contents = File.ReadAllBytes(Directory.GetCurrentDirectory() + "/hello.zip");
            var code = new Code(Convert.ToBase64String(contents));
            client.CreateFunction(new CreateFunctionRequest(Service, Function, "python3", "index.handler", code, "desc"));

            string triggerName = "my-cdn-trigger";

            var filter = new Dictionary<string, string[]>
            {
                { "filter",  new string[] { "www.taobao.com”,”www.tmall.com" }},
            };

            var cdnTriggerConfig = new CdnEventsTriggerConfig("LogFileCreated", "1.0.0", "cdn events trigger test", filter);
            string sourceArn = string.Format("acs:cdn:*:{0}", tf.AccountID);
            var response = client.CreateTrigger(new CreateTriggerRequest(Service, Function, triggerName, "cdn_events",
                                     sourceArn, tf.InvocationRole, cdnTriggerConfig, "cdn events trigger desc"));

            this.Triggers.Add(triggerName);

            replacedert.Equal(triggerName, response.Data.TriggerName);
            replacedert.Equal("cdn events trigger desc", response.Data.Description);
            replacedert.Equal("cdn_events", response.Data.TriggerType);
            replacedert.Equal(sourceArn, response.Data.SourceArn);
            replacedert.Equal(tf.InvocationRole, response.Data.InvocationRole);
            replacedert.Equal(JsonConvert.DeserializeObject<CdnEventsTriggerConfig>(response.Data.TriggerConfig.ToString()), cdnTriggerConfig);
        }

19 Source : VersionTest.cs
with MIT License
from aliyun

[Fact]
        public void TestGetFunction()
        {
            tf.Client.CreateService(new CreateServiceRequest(Service));

            string name = "test-csharp-func" + TestConfig.RandomString(8);
            byte[] contents = File.ReadAllBytes(Directory.GetCurrentDirectory() + "/hello.zip");
            var code = new Code(Convert.ToBase64String(contents));
            var response = tf.Client.CreateFunction(new CreateFunctionRequest(Service, name, "python3", "index.handler", code, "desc"));
            replacedert.Equal(200, response.StatusCode);
            var response2 = tf.Client.PublishVersion(new PublishVersionRequest(Service, "C# fc sdk 1"));
            replacedert.Equal(200, response2.StatusCode);
            var response3 = tf.Client.CreateAlias(new CreateAliasRequest(Service, "staging", response2.Data.VersionId, "alias desc"));
            replacedert.Equal(200, response3.StatusCode);

            var resp1 = tf.Client.PutProvisionConfig(new PutProvisionConfigRequest(Service, "staging", name, 10));
            replacedert.Equal(200, resp1.StatusCode);
            replacedert.Equal(10, resp1.Data.Target);

            var resp2 = tf.Client.GetProvisionConfig(new GetProvisionConfigRequest(Service, "staging", name));
            replacedert.Equal(200, resp2.StatusCode);
            replacedert.Equal(10, resp2.Data.Target);

            var resp3 = tf.Client.ListProvisionConfigs(new ListProvisionConfigsRequest(Service, "staging"));
            replacedert.Equal(200, resp3.StatusCode);
            replacedert.Equal(1, resp3.Data.ProvisionConfigs.GetLength(0));
            replacedert.Equal(10, resp3.Data.ProvisionConfigs[0].Target);
            replacedert.True(string.IsNullOrEmpty(resp3.Data.NextToken));

            resp1 = tf.Client.PutProvisionConfig(new PutProvisionConfigRequest(Service, "staging", name, 0));
            replacedert.Equal(200, resp1.StatusCode);
            replacedert.Equal(0, resp1.Data.Target);

            var response4 = tf.Client.GetFunction(new GetFunctionRequest(Service, name));
            replacedert.Equal("desc", response4.Data.Description);

            var response5 = tf.Client.GetFunction(new GetFunctionRequest(Service, name, response2.Data.VersionId));
            replacedert.Equal("desc", response5.Data.Description);

            var response6 = tf.Client.GetFunction(new GetFunctionRequest(Service, name, "staging"));
            replacedert.Equal("desc", response6.Data.Description);

            tf.Client.UpdateFunction(new UpdateFunctionRequest(Service, name, "python3", "index.handler", code, "new-desc"));
            var response7 = tf.Client.PublishVersion(new PublishVersionRequest(Service, "C# fc sdk 2"));
            tf.Client.CreateAlias(new CreateAliasRequest(Service, "prod", response7.Data.VersionId, "alias desc 2"));

            var response8 = tf.Client.GetFunction(new GetFunctionRequest(Service, name, response7.Data.VersionId));
            replacedert.Equal("new-desc", response8.Data.Description);

            var response9 = tf.Client.GetFunction(new GetFunctionRequest(Service, name, "prod"));
            replacedert.Equal("new-desc", response9.Data.Description);

        }

19 Source : VersionTest.cs
with MIT License
from aliyun

[Fact]
        public void TestInvokeFunction()
        {
            tf.Client.CreateService(new CreateServiceRequest(Service));

            string name = "test-csharp-func" + TestConfig.RandomString(8);
            byte[] contents = File.ReadAllBytes(Directory.GetCurrentDirectory() + "/hello.zip");
            var code = new Code(Convert.ToBase64String(contents));
            tf.Client.CreateFunction(new CreateFunctionRequest(Service, name, "python3", "index.handler", code, "desc"));
            byte[] hello = Encoding.UTF8.GetBytes("hello csharp world");
            var response = tf.Client.InvokeFunction(new InvokeFunctionRequest(Service, name, null, hello));
            replacedert.Equal("hello csharp world", response.Content);
            replacedert.Equal(hello, response.Data);

            var response2 = tf.Client.PublishVersion(new PublishVersionRequest(Service, "C# fc sdk 1"));
            replacedert.Equal(200, response2.StatusCode);
            var response3 = tf.Client.CreateAlias(new CreateAliasRequest(Service, "staging", response2.Data.VersionId, "alias desc"));
            replacedert.Equal(200, response3.StatusCode);

            var response4 = tf.Client.InvokeFunction(new InvokeFunctionRequest(Service, name, "staging", hello));
            replacedert.Equal("hello csharp world", response4.Content);
            replacedert.Equal(hello, response4.Data);

            var response5 = tf.Client.InvokeFunction(new InvokeFunctionRequest(Service, name, response2.Data.VersionId, hello));
            replacedert.Equal("hello csharp world", response5.Content);
            replacedert.Equal(hello, response5.Data);
        }

19 Source : TorrentInfo.cs
with MIT License
from aljazsim

public static bool TryLoad(string torrentInfoFilePath, out TorrentInfo torrentInfo)
        {
            torrentInfoFilePath.MustBeValidFilePath();
            torrentInfoFilePath.MustFileExist();

            return TryLoad(File.ReadAllBytes(torrentInfoFilePath), out torrentInfo);
        }

19 Source : PdfImageConverter.cs
with MIT License
from allantargino

public void GenerateImage(Stream pdfInput, ref Stream[] imageListOutput)
        {
            if (!pdfInput.CanSeek) throw new Exception("PdfInput Stream can not be seek!");

            var rand = new Random(DateTime.Now.Second);

            int value = rand.Next();
            string tempPrefix = $"dou_pdf_temp_{value}";
            string pdfDirectory = $@"{_tempFolder}\{tempPrefix}";
            string pdfFileName = $"{tempPrefix}.pdf";

            var pdfFile = ToFile(pdfInput, pdfFileName);

            var images = ConvertAsync(pdfFile.FullName, _ratio).GetAwaiter().GetResult();

            Console.Write($"Images generated: {images.Length}");

            if (images == null)
            {
                Console.WriteLine("Error generating the images!");
                return;
            }

            imageListOutput = new Stream[images.Length];

            for (var i = 0; i < images.Length; i++)
            {                 
                var bytes = File.ReadAllBytes(images[i]);
                MemoryStream jpgMemory = new MemoryStream(bytes);

                //As the images are not in the proper order it is necessary to retrieve the page index.
                var parts = images[i].Replace(".jpg", "").Split('_');
                int pageIdx = int.Parse(parts[parts.Length - 1]);

                imageListOutput[pageIdx - 1] = jpgMemory;
                File.Delete(images[i]);
            }

            try
            {
                Directory.Delete($@"{pdfDirectory}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Erro deleting directory {pdfDirectory} - {ex.Message}");
                throw new Exception(ex.Message, ex);
            }
        }

19 Source : AllureLifecycle.cs
with Apache License 2.0
from allure-framework

public virtual AllureLifecycle AddAttachment(string name, string type, string path)
        {
            var fileExtension = new FileInfo(path).Extension;
            return AddAttachment(name, type, File.ReadAllBytes(path), fileExtension);
        }

19 Source : DataGenerator.cs
with Apache License 2.0
from allure-framework

internal static (string path, byte[] content) GetAttachment(string extension = "")
        {
            var path = $"{Guid.NewGuid().ToString()}{extension}";
            var content = "test";
            File.WriteAllText(path, content);
            return (path, File.ReadAllBytes(path));
        }

19 Source : GoldenTest.cs
with Apache License 2.0
from aloneguid

[Fact]
      public void EncodeGoldenInput()
      {
         byte[] got = Snappy.Encode(File.ReadAllBytes("TestData/Mark.Twain-Tom.Sawyer.txt"));

         byte[] want = File.ReadAllBytes("TestData/Mark.Twain-Tom.Sawyer.rawsnappy.txt");

         replacedert.Equal(want.Length, got.Length);

         replacedert.Equal(want, got);
      }

19 Source : GoldenTest.cs
with Apache License 2.0
from aloneguid

[Fact]
      public void DecodeGoldenInput()
      {
         byte[] got = Snappy.Decode(File.ReadAllBytes("TestData/Mark.Twain-Tom.Sawyer.rawsnappy.txt"));

         byte[] want = File.ReadAllBytes("TestData/Mark.Twain-Tom.Sawyer.txt");

         replacedert.Equal(want.Length, got.Length);

         replacedert.Equal(want, got);
      }

19 Source : GoldenTest.cs
with Apache License 2.0
from aloneguid

[Fact]
      public void RoundtripGoldenData()
      {
         byte[] goldenRaw = File.ReadAllBytes("TestData/Mark.Twain-Tom.Sawyer.txt");
         byte[] compressed = Snappy.Encode(goldenRaw);
         byte[] uncompressed = Snappy.Decode(compressed);

         replacedert.Equal(goldenRaw.Length, uncompressed.Length);
         replacedert.Equal(goldenRaw, uncompressed);
      }

19 Source : GoldenTest.cs
with Apache License 2.0
from aloneguid

[Fact]
      public void RoundtripEncodeBytes()
      {
         byte[] bytes = File.ReadAllBytes("TestData/Mark.Shanghai-skyyearxp.bytes");
         byte[] wants = File.ReadAllBytes("TestData/Mark.Shanghai-skyyearxp.snappy.bytes");

         byte[] compressed = Snappy.Encode(bytes);
         replacedert.Equal(wants.Length, compressed.Length);
         replacedert.Equal(wants, compressed);

         byte[] uncompressed = Snappy.Decode(compressed);
         replacedert.Equal(bytes.Length, uncompressed.Length);
         replacedert.Equal(bytes, uncompressed);
      }

19 Source : SYS_MASTER.cs
with GNU General Public License v3.0
from Alpaca-Studio

public static Texture2D LoadImageAtPath(string path){
			Texture2D tex;
			byte[] bytes;
			bytes = File.ReadAllBytes(path);
			tex = new Texture2D(1,1);
			tex.LoadImage(bytes);
			return tex;
		}

19 Source : Serializer.cs
with MIT License
from Alprog

public T DeserializeFromFile<T>(string path, SerializationSettings settings = default)
        {
            var bytes = File.ReadAllBytes(path);
            return Deserialize<T>(bytes, settings);
        }

19 Source : GameState.cs
with MIT License
from Alprog

public void LoadInitialState()
        {
            Clear();

            GameData = new GameData();

            byte[] bytes;
            SerializationSettings settings;

#if UNITY_EDITOR
            if (Application.isPlaying)
            {
                bytes = File.ReadAllBytes(Config.TempEditorStateFile);
                settings = new SerializationSettings(SerializationMode.LoadStaticPackage);
            }
            else
            {
                bytes = File.ReadAllBytes(Config.StaticDistributedFile);
                settings = new SerializationSettings(SerializationMode.LoadStaticFolder);
                settings.DistributedFolder = Config.StaticDistributedFolder;
                EditorOptions.LastDataBaseSyncTime = DateTime.UtcNow;
            }
#else
            bytes = File.ReadAllBytes(StaticBuildPackageFile);
            settings = new SerializationSettings(SerializationMode.LoadStaticPackage);
#endif
            Serializer.Instance.Deserialize<GameState>(bytes, settings, KeepOriginalState);
        }

19 Source : GameState.cs
with MIT License
from Alprog

public void LoadTempEditorState()
        {
            try
            {   
                Clear();
                GameData = new GameData();
                var bytes = File.ReadAllBytes(Config.TempEditorStateFile);
                var settings = new SerializationSettings(SerializationMode.LoadStaticPackage);
                Serializer.Instance.Deserialize<GameState>(bytes, settings, KeepOriginalState);
            }
            catch (Exception ex)
            {
                Debug.LogError("There was error when tried to load temp editor state! StackTrace: " + ex.Message + " " + ex.StackTrace);
                LoadInitialState();
            }
        }

19 Source : FileSystemCache.cs
with MIT License
from Alprog

public static FileCache GetFileCache(string path)
        {
            if (!File.Exists(path))
            {
                return null;
            }

            var time = File.GetLastWriteTimeUtc(path);

            if (FileCaches.TryGetValue(path, out var fileCache))
            {
                if (time == fileCache.LastWriteTime)
                {
                    return fileCache;
                }
            }

            var bytes = File.ReadAllBytes(path);
            fileCache = new FileCache(time, bytes);
            FileCaches[path] = fileCache;
            return fileCache;
        }

19 Source : AppResourcesSI.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn

private byte[] ReadFileByte(string fileName)
        {
            byte[] filedata = null;
            if (File.Exists(fileName))
            {
                filedata = File.ReadAllBytes(fileName);
            }

            return filedata;
        }

19 Source : AppResourcesSI.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn

private byte[] ReadFileContentsFromLegalPath(string legalPath, string filePath)
        {
            var fullFileName = legalPath + filePath;
            if (!PathHelper.ValidateLegalFilePath(legalPath, fullFileName))
            {
                throw new ArgumentException("Invalid argument", nameof(filePath));
            }

            if (File.Exists(fullFileName))
            {
                return File.ReadAllBytes(fullFileName);
            }

            return null;
        }

19 Source : AppResourcesSI.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn

public byte[] GetRuntimeResource(string resource)
        {
            byte[] fileContent = null;
            string path;
            if (resource == _settings.RuntimeAppFileName)
            {
                path = Path.Combine(_hostingEnvironment.WebRootPath, "runtime", "js", "react", _settings.RuntimeAppFileName);
            }
            else if (resource == _settings.ServiceStylesConfigFileName)
            {
                return Encoding.UTF8.GetBytes(_settings.GetStylesConfig());
            }
            else
            {
                path = Path.Combine(_hostingEnvironment.WebRootPath, "runtime", "css", "react", _settings.RuntimeCssFileName);
            }

            if (File.Exists(path))
            {
                fileContent = File.ReadAllBytes(path);
            }

            return fileContent;
        }

19 Source : PerformanceAnalyze.cs
with MIT License
from AlturosDestinations

private void Check(GpuConfig gpuConfig)
        {
            var yoloWrapper = new YoloWrapper("yolov2-tiny-voc.cfg", "yolov2-tiny-voc.weights", "voc.names", gpuConfig);
            var files = Directory.GetFiles(@".\Images");

            var retrys = 10;

            var sw = new Stopwatch();
            foreach (var file in files)
            {
                var elapsed = 0.0;
                var fileInfo = new FileInfo(file);
                var imageData = File.ReadAllBytes(file);

                for (var i = 0; i < retrys; i++)
                {
                    sw.Restart();
                    yoloWrapper.Detect(imageData);
                    sw.Stop();

                    elapsed += sw.Elapsed.TotalMilliseconds;
                }

                var average = elapsed / retrys;
                Console.WriteLine($"{fileInfo.Name} {average}ms");
            }

            yoloWrapper.Dispose();
        }

19 Source : Main.cs
with MIT License
from AlturosDestinations

private List<YoloItem> Detect(bool memoryTransfer = true)
        {
            if (this._yoloWrapper == null)
            {
                return null;
            }

            var imageInfo = this.GetCurrentImage();
            var imageData = File.ReadAllBytes(imageInfo.Path);

            var sw = new Stopwatch();
            sw.Start();
            List<YoloItem> items;
            if (memoryTransfer)
            {
                items = this._yoloWrapper.Detect(imageData).ToList();
            }
            else
            {
                items = this._yoloWrapper.Detect(imageInfo.Path).ToList();
            }
            sw.Stop();
            this.groupBoxResult.Text = $"Result [ processed in {sw.Elapsed.TotalMilliseconds:0} ms ]";

            return items;
        }

19 Source : BasicTest.cs
with MIT License
from AlturosDestinations

[TestMethod]
        public void DetectFromFileData()
        {
            var configuration = new YoloConfigurationDetector().Detect();
            using (var yoloWrapper = new YoloWrapper(configuration))
            {
                var imageData = File.ReadAllBytes(this._imagePath);
                var items = yoloWrapper.Detect(imageData);
                replacedert.IsTrue(items.Count() > 0);
            }
        }

19 Source : PerformanceResizeAnalyze.cs
with MIT License
from AlturosDestinations

public void Start()
        {
            var yoloWrapper = new YoloWrapper("yolov2-tiny-voc.cfg", "yolov2-tiny-voc.weights", "voc.names");
            var files = Directory.GetFiles(@".\Images");
            var imageResizer = new ImageResizer();

            var retrys = 10;

            Console.WriteLine(string.Format("|{0,20}|{1,29}|{2,43}|", "", "Resize with yolo", "Resize before yolo"));
            Console.WriteLine(string.Format("|{0,20}|{1,15}|{2,13}|{3,15}|{4,13}|{5,13}|{6,10}|{7,10}|", "Image", "detected items", "elapsed (ms)", " detected items", "resize (ms)", "yolo (ms)", "diff (ms)", "faster"));

            foreach (var file in files)
            {
                for (var i = 0; i < retrys; i++)
                {
                    var fileInfo = new FileInfo(file);
                    var imageData = File.ReadAllBytes(file);

                    var result1 = this.ProcessResizeAfter(yoloWrapper, imageData);
                    var result2 = this.ProcessResizeBefore(yoloWrapper, imageResizer, imageData);
                    var diff = result1.Item3 - result2.Item4;

                    Console.WriteLine(string.Format("|{0,20}|{1,15}|{2,13}|{3,15}|{4,13}|{5,13}|{6,10}|{7,10}|", fileInfo.Name, result1.Item1.Count, result1.Item2, result2.Item1.Count, result2.Item2, result2.Item3, diff.ToString("0.00"), diff > 0));
                }
            }

            yoloWrapper.Dispose();
        }

19 Source : SystemModule.cs
with GNU General Public License v3.0
from am0nsec

public bool LoadModule() {
            if (string.IsNullOrEmpty(this.ModuleName)) {
                Util.LogError("Module name not provided");
                return false;
            }

            if (!File.Exists(this.ModulePath)) {
                Util.LogError($"Unable to find module: {this.ModuleName}");
                return false;
            }

            ReadOnlySpan<byte> ModuleBlob = File.ReadAllBytes(this.ModulePath);
            if (ModuleBlob.Length == 0x00) {
                Util.LogError($"Empty module content: {this.ModuleName}");
                return false;
            }

            base.ModuleStream = new MemoryStream(ModuleBlob.ToArray());
            return true;
        }

19 Source : MmlMidiConventer.cs
with GNU General Public License v2.0
from AmanoTooko

public static byte[] mmlRead(string mmlPath)
		{

			mml2midi c = new mml2midi();
			var ret = 0;
			var midiPath = mmlPath.Replace(".mml", ".mid");
			var text = File.ReadAllText(mmlPath);
			if(text.Contains("MML@"))
			{
				unsafe
				{
					try
					{
						fixed (byte* b1 = (Encoding.Default.GetBytes(mmlPath)),
						b2 = Encoding.Default.GetBytes(midiPath))
						{
							ret = c.convert((sbyte*)b1, (sbyte*)b2);
						}
					}
					catch (Exception)
					{

						return null;
					}


				}
			}
			else
			{
				try
				{
					var sources = new List<MmlInputSource>();
					sources.Add(new MmlInputSource("fake.mml", new StringReader(File.ReadAllText(mmlPath))));
					using (var outs = new MemoryStream())
					{
						new MmlCompiler().Compile(false, sources, null, outs, false);
						return outs.ToArray();
					}
				}
				catch (Exception e)
				{
					return null;

				}
			}
			if (ret == 0)
			{

				var mmlOut = File.ReadAllBytes(midiPath);
				File.Delete(midiPath);
				return mmlOut;

			}
			return null;
			
		}

19 Source : BinaryPatcher.cs
with MIT License
from amazingalek

public byte[] ReadFileBytes()
		{
			var filePath = $"{_owmlConfig.DataPath}/{FileName}";
			if (!File.Exists(filePath))
			{
				throw new FileNotFoundException(filePath);
			}

			return File.ReadAllBytes(filePath);
		}

19 Source : ModAssets.cs
with MIT License
from amazingalek

public Texture2D GetTexture(string filename)
		{
			var path = _manifest.ModFolderPath + filename;
			_console.WriteLine($"Loading texture from {path}");
			var data = File.ReadAllBytes(path);
			var texture = new Texture2D(2, 2);
			texture.LoadImage(data);
			return texture;
		}

19 Source : ShaderIncludeHandler.cs
with MIT License
from amerkoleci

private static byte[] NewMethod(string includeFile) => File.ReadAllBytes(includeFile);

19 Source : Interface.cs
with MIT License
from Aminator

private static Func<string, Byte[]> GetExternalFileSolver(string gltfFilePath)
        {
            return replacedet =>
            {
                if (string.IsNullOrEmpty(replacedet)) return LoadBinaryBuffer(gltfFilePath);
                var bufferFilePath = Path.Combine(Path.GetDirectoryName(gltfFilePath), replacedet);
                return File.ReadAllBytes(bufferFilePath);
            };
        }

19 Source : LocalFileStorageService.cs
with MIT License
from amoraitis

public Task<FileStorageInfo> GetFileInfoAsync(string path)
        {
            if (String.IsNullOrEmpty(path))
                throw new ArgumentNullException(nameof(path));

            try
            {
                return Task.FromResult(new FileStorageInfo()
                {
                    Path = path,
                    Size = File.ReadAllBytes(Path.Combine(_basePath, path)).LongLength // Maybe slower than reading the FileInfo and returning the Length
                });
            }
            catch (Exception)
            {
                return null;
            }
        }

19 Source : ProjectNotifier.cs
with Apache License 2.0
from AmpScm

internal void HandleEvent(AnkhCommand command)
        {
            List<SccProject> dirtyProjects;
            HybridCollection<string> dirtyCheck;
            HybridCollection<string> maybeAdd;

            SvnSccProvider provider = GetService<SvnSccProvider>();

            lock (_lock)
            {
                _posted = false;
                _onIdle = false;

                if (provider == null)
                    return;

                dirtyProjects = _dirtyProjects;
                dirtyCheck = _dirtyCheck;
                maybeAdd = _maybeAdd;
                _dirtyProjects = null;
                _dirtyCheck = null;
                _maybeAdd = null;
            }

            if (dirtyCheck != null)
                foreach (string file in dirtyCheck)
                {
                    DoreplacedentTracker.CheckDirty(file);
                }

            if (dirtyProjects != null)
            {
                foreach (SccProject project in dirtyProjects)
                {
                    if (project.IsSolution)
                        provider.UpdateSolutionGlyph();
                    else
                        project.NotifyGlyphChanged();
                }
            }

            if (maybeAdd != null)
            {
                using (SvnClient cl = GetService<ISvnClientPool>().GetNoUIClient())
                {
                    foreach (string file in maybeAdd)
                    {
                        SvnItem item = SvnCache[file];
                        // Only add
                        // * files
                        // * that are unversioned
                        // * that are addable
                        // * that are not ignored
                        // * and just to be sure: that are still part of the solution
                        if (item.IsFile && !item.IsVersioned &&
                            item.IsVersionable && !item.IsIgnored &&
                            item.InSolution && !item.IsSccExcluded)
                        {
                            SvnAddArgs aa = new SvnAddArgs();
                            aa.ThrowOnError = false; // Just ignore errors here; make the user add them themselves
                            aa.AddParents = true;

                            if (cl.Add(item.FullPath, aa))
                            {
                                item.MarkDirty();

                                // Detect if we have a file that Subversion might detect as binary
                                if (item.IsVersioned && !item.IsTextFile)
                                {
                                    // Only check small files, avoid checking big binary files
                                    FileInfo fi = new FileInfo(item.FullPath);
                                    if (fi.Length < 10)
                                    {
                                        // We're sure it's at most 10 bytes here, so just read all
                                        byte[] fileBytes = File.ReadAllBytes(item.FullPath);

                                        // If the file starts with a UTF8 BOM, we're sure enough it's a text file, keep UTF16 & 32 binary
                                        if (StartsWith(fileBytes, new byte[] { 0xEF, 0xBB, 0xBF }))
                                        {
                                            // Delete the mime type property, so it's detected as a text file again
                                            SvnSetPropertyArgs pa = new SvnSetPropertyArgs();
                                            pa.ThrowOnError = false;
                                            cl.DeleteProperty(item.FullPath, SvnPropertyNames.SvnMimeType, pa);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

19 Source : MainForm.cs
with Mozilla Public License 2.0
from amrali-eg

private void OnConvert(object sender, EventArgs e)
        {
            if (lstResults.CheckedItems.Count == 0)
            {
                ShowWarning("Select one or more files to convert");
                return;
            }

            // stop drawing of the results list view control
            lstResults.BeginUpdate();
            lstResults.ItemChecked -= OnResulreplacedemChecked;

            foreach (ListViewItem item in lstResults.CheckedItems)
            {
                string charset = item.SubItems[RESULTS_COLUMN_CHARSET].Text;
                if (charset == "(Unknown)")
                    continue;
                string fileName = item.SubItems[RESULTS_COLUMN_FILE_NAME].Text;
                string directory = item.SubItems[RESULTS_COLUMN_DIRECTORY].Text;
                string filePath = Path.Combine(directory, fileName);

                FileAttributes attributes = File.GetAttributes(filePath);
                if ((attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
                {
                    attributes ^= FileAttributes.ReadOnly;
                    File.SetAttributes(filePath, attributes);
                }

                if (!Encoding.GetEncoding(charset).Validate(File.ReadAllBytes(filePath)))
                {
                    Debug.WriteLine("Decoding error. " + filePath);
                    continue;
                }

                string content;
                using (StreamReader reader = new StreamReader(filePath, Encoding.GetEncoding(charset)))
                    content = reader.ReadToEnd();

                string targetCharset = (string)lstConvert.SelectedItem;
                Encoding encoding;
                // handle UTF-8 and UTF-8 with BOM
                if (targetCharset == "utf-8")
                {
                    encoding = new UTF8Encoding(false);
                }
                else if (targetCharset == "utf-8-bom")
                {
                    encoding = new UTF8Encoding(true);
                }
                else
                {
                    encoding = Encoding.GetEncoding(targetCharset);
                }
                using (StreamWriter writer = new StreamWriter(filePath, append: false, encoding))
                {
                    // TODO: catch exceptions
                    writer.Write(content);
                    writer.Flush();
                }

                item.Checked = false;
                item.ImageIndex = 0;
                item.SubItems[RESULTS_COLUMN_CHARSET].Text = targetCharset;
            }

            // resume drawing of the results list view control
            lstResults.ItemChecked += OnResulreplacedemChecked;
            lstResults.EndUpdate();

            // execute handler of the 'ItemChecked' event
            OnResulreplacedemChecked(lstResults, new ItemCheckedEventArgs(lstResults.Items[0]));
        }

19 Source : AnalogyMessagePackFormat.cs
with MIT License
from Analogy-LogViewer

public async Task<IEnumerable<replacedogyLogMessage>> ReadFromFile(string fileName, CancellationToken token, ILogMessageCreatedHandler messageHandler)
        {

            if (string.IsNullOrEmpty(fileName))
            {
                replacedogyLogMessage empty = new replacedogyLogMessage($"File is null or empty. Aborting.",
                    replacedogyLogLevel.Critical, replacedogyLogClreplaced.General, "replacedogy", "None")
                {
                    Source = "replacedogy",
                    Module = Process.GetCurrentProcess().ProcessName
                };
                messageHandler.AppendMessage(empty, Utils.GetFileNameAsDataSource(fileName));
                return new List<replacedogyLogMessage>() { empty };
            }

            return await Task<IEnumerable<replacedogyLogMessage>>.Factory.StartNew(() =>
            {
                try
                {
                    byte[] data = File.ReadAllBytes(fileName);
                    var messages = MessagePackSerializer.Deserialize < List<replacedogyLogMessage>>(data, MessagePack.Resolvers.ContractlessStandardResolver.Options);
                    messageHandler.AppendMessages(messages, Utils.GetFileNameAsDataSource(fileName));
                    return messages;
                }
                catch (Exception ex)
                {

                    replacedogyLogMessage empty =
                        new replacedogyLogMessage($"File {fileName} is empty or corrupted. Error: {ex.Message}",
                            replacedogyLogLevel.Error, replacedogyLogClreplaced.General, "replacedogy", "None")
                        {
                            Source = "replacedogy",
                            Module = Process.GetCurrentProcess().ProcessName
                        };
                    replacedogyLogManager.Instance.LogErrorMessage(empty);
                    messageHandler.AppendMessage(empty, Utils.GetFileNameAsDataSource(fileName));
                    return new List<replacedogyLogMessage>() { empty };
                }
            }, token);

        }

19 Source : DeviceImageLoadContext.cs
with MIT License
from ancientproject

protected override replacedembly Load(replacedemblyName replacedemblyName)
        {
            var imageName = replacedemblyName.Name;
            var fullImageName = $"{replacedemblyName.Name}.image";
            var imageVersion = replacedemblyName.Version;
            var file = FindImage(imageName, imageVersion);
            if (file is null)
                throw new Exception($"can't load '{fullImageName}' - [not found].");
            log($"'{fullImageName}' was found in '{file}' and success loaded");
            var asm = replacedembly.Load(File.ReadAllBytes(file.FullName));
            return asm;
        }

19 Source : Program.cs
with MIT License
from ancientproject

public static void InitializeMemory(Bus bus, params string[] args)
        {
            if (bus.State.halt != 0)
                return;
            if (!args.Any())
                bus.State.Load("<chip>", 0xB00B50000);
            else
            {
                var nameFile = Path.Combine(Path.GetDirectoryName(args.First()), Path.GetFileNameWithoutExtension(args.First()));
                var file = new FileInfo($"{nameFile}.dlx");
                var bios = new FileInfo($"{nameFile}.bios");
                var pdb = new FileInfo($"{nameFile}.pdb");

                if (AppFlag.GetVariable("VM_ATTACH_DEBUGGER") && pdb.Exists)
                    bus.AttachDebugger(new Debugger(DebugSymbols.Open(File.ReadAllBytes(pdb.FullName))));
                if (bios.Exists)
                {
                    var asm = Ancientreplacedembly.LoadFrom(bios.FullName);
                    var bytes = asm.GetILCode();
                    var meta = asm.GetMetaILCode();
                    bus.State.Load("<bios>", CastFromBytes(bytes));
                    bus.State.LoadMeta(meta);
                }
                if (file.Exists)
                {
                    var asm = Ancientreplacedembly.LoadFrom(file.FullName);
                    var bytes = asm.GetILCode();
                    var meta = asm.GetMetaILCode();
                    bus.State.Load("<exec>", CastFromBytes(bytes));
                    bus.State.LoadMeta(meta);
                }
                else
                    bus.State.Load("<chip>", 0xB00B5000);
            }
        }

19 Source : ResourceRedirectManager.cs
with GNU General Public License v3.0
from AndrasMumm

private Texture2D LoadTexture2D(string path)
        {
            if (path.StartsWith("replacedets/") || path.StartsWith("replacedets/"))
            {
                path = path.Substring(7);
            }

            if (_replacedetCache.ContainsKey(path))
            {
                return _replacedetCache[path] as Texture2D;
            }

            if (!ExistsRedirect(path))
            {
                return default;
            }

            string rootRedirect = GetRedirect(path);
            string absolutePath = Paths.GameRootPath + Path.DirectorySeparatorChar + rootRedirect + Path.DirectorySeparatorChar + path;

            byte[] data = File.ReadAllBytes(absolutePath);
            Texture2D texture2D = new Texture2D(2, 2);
            texture2D.LoadImage(data);

            _replacedetCache[path] = texture2D;

            return texture2D;
        }

19 Source : ResourceRedirectManager.cs
with GNU General Public License v3.0
from AndrasMumm

private Sprite LoadSprite(string path)
        {
            if (path.StartsWith("replacedets/") || path.StartsWith("replacedets/"))
            {
                path = path.Substring(7);
            }

            if (_replacedetCache.ContainsKey(path))
            {
                return _replacedetCache[path] as Sprite;
            }

            if (!ExistsRedirect(path))
            {
                return default;
            }

            string rootRedirect = GetRedirect(path);
            string absolutePath = Paths.GameRootPath + Path.DirectorySeparatorChar + rootRedirect + Path.DirectorySeparatorChar + path;

            byte[] data = File.ReadAllBytes(absolutePath);
            Texture2D texture2D = new Texture2D(2, 2);
            texture2D.LoadImage(data);

            Sprite sprite = Sprite.Create(texture2D, new Rect(0f, 0f, (float)texture2D.width, (float)texture2D.height), new Vector2((float)(texture2D.width / 2), (float)(texture2D.height / 2)));

            _replacedetCache[path] = sprite;
            return sprite;
        }

19 Source : ResourceRedirectManager.cs
with GNU General Public License v3.0
from AndrasMumm

public void replacedetLoaded(replacedetLoadedContext context)
        {
            //Debug.LogError("replacedetLoaded: " + context.Parameters.Name);
            if (!_ForceOriginalNextLoad && Path.GetExtension(context.Parameters.Name) == ".prefab")
            {
                //It is a prefab, we want to check for child GameObjects and replace them if needed
                GameObject prefab = context.replacedet as GameObject;
                Component[] allChildren = prefab.GetComponentsInChildren(typeof(Component));
                //Debug.Log("Prefab: " + context.Parameters.Name);
                foreach (Component child in allChildren)
                {
                    if (child == null) continue;

                    //Checking if we can replace the content of the component based on the type of the component
                    Type childType = child.GetType();
                    if (childType == typeof(UnityEngine.UI.Image))
                    {
                        //It is an Image, checking if we can replace the image.
                        UnityEngine.UI.Image childImage = child as UnityEngine.UI.Image;
                        if (childImage.sprite != null)
                        {
                            string originalSpriteName = childImage.sprite.name;
                            string imageFileName = originalSpriteName + ".png";
                            if (replacedetNameToPath.ContainsKey(imageFileName))
                            {
                                string path = replacedetNameToPath[imageFileName];
                                if (ExistsRedirect(path))
                                {
                                    //We have a replacement for the sprite
                                    //Debug.Log("Overriding the texture of the over Prefab loaded Sprite  " + childImage.sprite.name + " with the texture " + path);
                                    //Overwritting Sprite Texture
                                    string rootRedirect = GetRedirect(path);
                                    string absolutePath = Paths.GameRootPath + Path.DirectorySeparatorChar + rootRedirect + Path.DirectorySeparatorChar + path;
                                    childImage.sprite.texture.LoadImage(File.ReadAllBytes(absolutePath), false);
                                }
                                else
                                {
                                    //Debug.Log("Could not find prefab redirect for image from path " + path);
                                }
                            }
                            else
                            {
                                //Debug.Log("Could not find prefab redirect for image file " + imageFileName + " from bundle " + context.Bundle.name);
                            }
                        }
                    }
                }
            }

            _ForceOriginalNextLoad = false;
            context.Complete(false);
        }

19 Source : DataManagerRedirector.cs
with GNU General Public License v3.0
from AndrasMumm

public static bool Prefix(ref DataManager __instance, string path, ref IDictionary<Type, IDictionary> ___dict, ref IResourceProvider ___resource)
        {
            path = __instance.CheckPath(path);

            bool forceSimplified = ModAPI.ModAPI.GetInstance().Config_ForceSimplifiedChinese.Value;
            if (forceSimplified)
            {
                path = path.Replace("/cht/", "/chs/");
            }
            ___dict = new Dictionary<Type, IDictionary>();
            Type type = typeof(Item);
            foreach (Type dataType in from t in type.replacedembly.GetTypes() where t.IsSubclreplacedOf(type) && !t.HasAttribute<Hidden>(false) select t)
            {
                //Debug.Log("Loading " + dataType.Name);
                try
                {
                    IDictionary result;
                    if (!dataType.HasAttribute<JsonConfig>(false))
                    {
                        //It is a .txt file
                        Type csvDataSourceType = typeof(CsvDataSource<>).MakeGenericType(new Type[] { dataType });
                        string dataPath = path + dataType.Name + ".txt";
                        //First we load the original
                        var resourceRedirector = ResourceRedirectManager.GetInstance();
                        resourceRedirector.ForceOriginalLoadInNextLoad();
                        byte[] array = ___resource.LoadBytes(dataPath);
                        result = ((Activator.CreateInstance(csvDataSourceType, new object[] { array }) as IDictionary));

                        List<string> redirects = resourceRedirector.GetAllRedirects(dataPath);
                        //We iterate over every redirect, load it and then replace all entries with same ID.
                        if (redirects != null)
                        {
                            for (int i = 0; i < redirects.Count; ++i)
                            {
                                string rootRedirect = redirects[i];
                                string absolutePath = Paths.GameRootPath + Path.DirectorySeparatorChar + rootRedirect + Path.DirectorySeparatorChar + path + Path.DirectorySeparatorChar + dataType.Name + ".txt";
                                byte[] data = File.ReadAllBytes(absolutePath);
                                IDictionary redirectData = Activator.CreateInstance(csvDataSourceType, new object[] { data }) as IDictionary;
                                foreach (var id in redirectData.Keys)
                                {
                                    if (result.Contains(id))
                                    {
                                        //Debug.Log("Replacing entry " + id);
                                        //Overwritting
                                        result[id] = redirectData[id];
                                    }
                                    else
                                    {
                                        Debug.LogWarning("Adding new custom entry " + id);
                                        result.Add(id, redirectData[id]);
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        //It is a .json file, we do NOT allow partial overwritting of these, we just use the normal resource provider, which should be handled by the ResourceRedirectManager
                        string dataPath = "Config/" + dataType.Name + ".json";
                        byte[] array = ___resource.LoadBytes(dataPath);
                        if (array == null)
                        {
                            Debug.LogWarning("DataManager tried to load " + dataPath + " but it was not successful!");
                            continue;
                        }

                        string utf8Data = Encoding.UTF8.GetString(array);
                        Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(new Type[] { typeof(string), dataType });
                        result = (JsonConvert.DeserializeObject(utf8Data, dictionaryType) as IDictionary);
                    }

                    ___dict.Add(dataType, result);
                }
                catch (ConvertException ex)
                {
                    Debug.LogError(string.Concat(new object[]
{
                        "Error while parsing ",
                        dataType.Name,
                        "!\r\nRow : ",
                        ex.LineNumber,
                        ", Column : ",
                        ex.ColumnNumber,
                        ", FieldType = ",
                        ex.FieldType.Name,
                        ", FieldName = ",
                        ex.FieldName,
                        "\r\n",
                        ex
                    }));
                }
                catch (Exception ex2)
                {
                    Debug.LogError(string.Concat(new object[]
                    {
                        "Error while parsing ",
                        dataType.Name,
                        " !\r\n",
                        ex2
                    }));
                }
            }
            //No need to call original
            return false;
        }

19 Source : ResourceRedirectManager.cs
with GNU General Public License v3.0
from AndrasMumm

private Textreplacedet LoadText(string path)
        {
            if (path.StartsWith("replacedets/") || path.StartsWith("replacedets/"))
            {
                path = path.Substring(7);
            }

            if (_replacedetCache.ContainsKey(path))
            {
                return _replacedetCache[path] as Textreplacedet;
            }

            if (!ExistsRedirect(path))
            {
                return default;
            }

            string rootRedirect = GetRedirect(path);
            string absolutePath = Paths.GameRootPath + Path.DirectorySeparatorChar + rootRedirect + Path.DirectorySeparatorChar + path;

            byte[] data = File.ReadAllBytes(absolutePath);
            Textreplacedet ta = new Textreplacedet(Encoding.UTF8.GetString(data, 0, data.Length));

            _replacedetCache[path] = ta;
            return ta;
        }

19 Source : HtmlConverter.cs
with MIT License
from andrei-m-code

public byte[] FromUrl(string url, int width = 1024, ImageFormat format = ImageFormat.Jpg, int quality = 100)
        {
            var imageFormat = format.ToString().ToLower();
            var filename = Path.Combine(directory, $"{Guid.NewGuid().ToString()}.{imageFormat}");

            string args;

            if (IsLocalPath(url))
            {
                args = $"--quality {quality} --width {width} -f {imageFormat} \"{url}\" \"{filename}\"";
            }
            else
            {
                args = $"--quality {quality} --width {width} -f {imageFormat} {url} \"{filename}\"";
            }

            Process process = Process.Start(new ProcessStartInfo(toolFilepath, args)
            {
                WindowStyle = ProcessWindowStyle.Hidden,
                CreateNoWindow = true,
                UseShellExecute = false,
                WorkingDirectory = directory,
                RedirectStandardError = true
            });

            process.ErrorDataReceived += Process_ErrorDataReceived;
            process.WaitForExit();

            if (File.Exists(filename))
            {
                var bytes = File.ReadAllBytes(filename);
                File.Delete(filename);
                return bytes;
            }

            throw new Exception("Something went wrong. Please check input parameters");
        }

19 Source : AvatarsHashCache.cs
with MIT License
from andruzzzhka

private static Task<string> CalculateHash(string path)
        {
            return Task.Run(() => {
                return BitConverter.ToString(MD5.Create().ComputeHash(File.ReadAllBytes(path))).Replace("-", "");
            });
        }

19 Source : HttpRequestEventArgs.cs
with MIT License
from andruzzzhka

private static bool tryReadFile (string path, out byte[] contents)
    {
      contents = null;

      if (!File.Exists (path))
        return false;

      try {
        contents = File.ReadAllBytes (path);
      }
      catch {
        return false;
      }

      return true;
    }

See More Examples