برچسب: Online

  • How to download an online file and store it on file system with C# | Code4IT

    How to download an online file and store it on file system with C# | Code4IT


    Downloading a file from a remote resource seems an easy task: download the byte stream and copy it to a local file. Beware of edge cases!

    Table of Contents

    Just a second! 🫷
    If you are here, it means that you are a software developer.
    So, you know that storage, networking, and domain management have a cost .

    If you want to support this blog, please ensure that you have disabled the adblocker for this site.
    I configured Google AdSense to show as few ADS as possible – I don’t want to bother you with lots of ads, but I still need to add some to pay for the resources for my site.

    Thank you for your understanding.
    Davide

    Downloading files from an online source and saving them on the local machine seems an easy task.

    And guess what? It is!

    In this article, we will learn how to download an online file, perform some operations on it – such as checking its file extension – and store it in a local folder. We will also learn how to deal with edge cases: what if the file does not exist? Can we overwrite existing files?

    How to download a file stream from an online resource using HttpClient

    Ok, this is easy. If you have the file URL, it’s easy to just download it using HttpClient.

    HttpClient httpClient = new HttpClient();
    Stream fileStream = await httpClient.GetStreamAsync(fileUrl);
    

    Using HttpClient can cause some trouble, especially when you have a huge computational load. As a matter of fact, using HttpClientFactory is preferred, as we’ve already explained in a previous article.

    But, ok, it looks easy – way too easy! There are two more parts to consider.

    How to handle errors while downloading a stream of data

    You know, shit happens!

    There are at least 2 cases that stop you from downloading a file: the file does not exist or the file requires authentication to be accessed.

    In both cases, an HttpRequestException exception is thrown, with the following stack trace:

    at System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()
    at System.Net.Http.HttpClient.GetStreamAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken)
    

    As you can see, we are implicitly calling EnsureSuccessStatusCode while getting the stream of data.

    You can tell the consumer that we were not able to download the content in two ways: throw a custom exception or return Stream.Null. We will use Stream.Null for the sake of this article.

    Note: always throw custom exceptions and add context to them: this way, you’ll add more useful info to consumers and logs, and you can hide implementation details.

    So, let me refactor the part that downloads the file stream and put it in a standalone method:

    async Task<Stream> GetFileStream(string fileUrl)
    {
        HttpClient httpClient = new HttpClient();
        try
        {
            Stream fileStream = await httpClient.GetStreamAsync(fileUrl);
            return fileStream;
        }
        catch (Exception ex)
        {
            return Stream.Null;
        }
    }
    

    so that we can use Stream.Null to check for the existence of the stream.

    How to store a file in your local machine

    Now we have our stream of data. We need to store it somewhere.

    We will need to copy our input stream to a FileStream object, placed within a using block.

    using (FileStream outputFileStream = new FileStream(path, FileMode.Create))
    {
        await fileStream.CopyToAsync(outputFileStream);
    }
    

    Possible errors and considerations

    When creating the FileStream instance, we have to pass the constructor both the full path of the image, with also the file name, and FileMode.Create, which tells the stream what type of operations should be supported.

    FileMode is an enum coming from the System.IO namespace, and has different values. Each value fits best for some use cases.

    public enum FileMode
    {
        CreateNew = 1,
        Create,
        Open,
        OpenOrCreate,
        Truncate,
        Append
    }
    

    Again, there are some edge cases that we have to consider:

    • the destination folder does not exist: you will get an DirectoryNotFoundException exception. You can easily fix it by calling Directory.CreateDirectory to generate all the hierarchy of folders defined in the path;
    • the destination file already exists: depending on the value of FileMode, you will see a different behavior. FileMode.Create overwrites the image, while FileMode.CreateNew throws an IOException in case the image already exists.

    Full Example

    It’s time to put the pieces together:

    async Task DownloadAndSave(string sourceFile, string destinationFolder, string destinationFileName)
    {
        Stream fileStream = await GetFileStream(sourceFile);
    
        if (fileStream != Stream.Null)
        {
            await SaveStream(fileStream, destinationFolder, destinationFileName);
        }
    }
    
    async Task<Stream> GetFileStream(string fileUrl)
    {
        HttpClient httpClient = new HttpClient();
        try
        {
            Stream fileStream = await httpClient.GetStreamAsync(fileUrl);
            return fileStream;
        }
        catch (Exception ex)
        {
            return Stream.Null;
        }
    }
    
    async Task SaveStream(Stream fileStream, string destinationFolder, string destinationFileName)
    {
        if (!Directory.Exists(destinationFolder))
            Directory.CreateDirectory(destinationFolder);
    
        string path = Path.Combine(destinationFolder, destinationFileName);
    
        using (FileStream outputFileStream = new FileStream(path, FileMode.CreateNew))
        {
            await fileStream.CopyToAsync(outputFileStream);
        }
    }
    

    Bonus tips: how to deal with file names and extensions

    You have the file URL, and you want to get its extension and its plain file name.

    You can use some methods from the Path class:

    string image = "https://website.come/csharptips/format-interpolated-strings/featuredimage.png";
    Path.GetExtension(image); // .png
    Path.GetFileNameWithoutExtension(image); // featuredimage
    

    But not every image has a file extension. For example, Twitter cover images have this format: https://pbs.twimg.com/profile_banners/1164441929679065088/1668758793/1080×360

    string image = "https://pbs.twimg.com/profile_banners/1164441929679065088/1668758793/1080x360";
    Path.GetExtension(image); // [empty string]
    Path.GetFileNameWithoutExtension(image); // 1080x360
    

    Further readings

    As I said, you should not instantiate a new HttpClient() every time. You should use HttpClientFactory instead.

    If you want to know more details, I’ve got an article for you:

    🔗 C# Tip: use IHttpClientFactory to generate HttpClient instances | Code4IT

    This article first appeared on Code4IT 🐧

    Wrapping up

    This was a quick article, quite easy to understand – I hope!

    My main point here is that not everything is always as easy as it seems – you should always consider edge cases!

    I hope you enjoyed this article! Let’s keep in touch on Twitter or on LinkedIn, if you want! 🤜🤛

    Happy coding!

    🐧





    Source link

  • Try an Online Browser! (For Free!)

    Try an Online Browser! (For Free!)


    TLDR: You can get instant access to an online browser at browserling.com/browse. It runs entirely in your own browser. No downloads, no installs.

    What’s An Online Browser?

    It’s a browser hosted elsewhere, streamed to you in real time. You use it like any regular browser, but it runs safely outside your device on a remote server.

    Is It Safe For Sketchy Sites?

    Absolutely. Any harmful scripts or shady behavior stay isolated on the remote machine. Your computer stays untouched and safe from viruses, malware, and phishing traps.

    Can I Test Suspicious Links?

    Yes, you can open any link inside an online browser without risking your own device. Using an online browser is one of the safest ways to check unknown URLs, especially if you’re worried about phishing or malware.

    What About Email Attachments?

    You can use an online browser to open files or attachments from emails without downloading them locally. This is a smart trick for checking PDFs or Office files that might contain malicious scripts.

    Is It Good For Cybersecurity?

    Absolutely. Online browsers are a big help for threat hunters and analysts. They let you investigate risky sites, test exploits, and open shady content without ever touching your network.

    Do I Need To Install Anything?

    No installation needed. It works instantly in your browser. Just click and go. No plugins, no setup, nothing to configure.

    Can I Test Different Browsers?

    Yes! You can choose from Chrome, Firefox, Edge, Safari, and more to test how sites look and behave across platforms. This is super useful for developers checking cross-browser compatibility, or QA testers fixing layout bugs.

    Is It Free?

    There’s a free version with time limits, and paid plans that unlock full access and extra features. The free plan is good for quick tasks, and the premium plans are built for teams, security testing, and daily use.

    Is It On GitHub?

    Yes. You can contribute to online browser repository on GitHub.

    What Is Browserling?

    Browserling is an online browser service that gives you instant access to real browsers running on remote systems. It’s made for testing, development, and secure browsing.

    Who Uses Browserling?

    Tech professionals around the world rely on Browserling. From cybersecurity experts and IT teams to cybersecurity experts exploring high-risk parts of the web. It’s trusted by millions each month, including major banks, universities, media outlets, government agencies, and Fortune 100 companies.

    Happy browsing!



    Source link

  • Online Browser Coupon Code (30% OFF)

    Online Browser Coupon Code (30% OFF)


    TLDR: You can grab a discount for Browserling (a super handy online browser) by using the coupon code ONLINEBROWSER at browserling.com. It gives you 30% off premium plans. Works for developers, hackers, testers, and anyone browsing online.

    What’s the Online Browser Coupon For?

    This code gives you a discount on Browserling‘s premium plans. If you’ve been using the free version but keep hitting the time limit, now’s your chance to upgrade. Just head to Browserling’s pricing page and enter ONLINEBROWSER when checking out.

    Why Use an Online Browser?

    It’s basically a browser that runs in the cloud. No installs, no setup. Just click and you’re inside a live Chrome, Firefox, Edge, or even Internet Explorer (yeah, really). It streams right into your browser.

    This is super useful when you:

    • Want to open sketchy links without risking your machine.
    • Need to cross-browser test websites in different browsers.
    • Get suspicious email attachments (open them here instead).
    • Need to do security research or open malware sites.
    • Work in dev, QA, pentesting, or sysadmin stuff.

    Is an Online Browser Safe?

    Yep. Everything runs in a sandbox on remote servers. If something explodes, it doesn’t affect your system. Your IP is hidden too, so it’s also good for private browsing.

    Pro Tip: Use It From a Chromebook

    An online browser works great on low-power machines like Chromebooks. Since the browser runs remotely, you can do full browser testing or malware link checking without needing a high-end laptop.

    What Is Browserling?

    Browserling is a secure online browser that lets you open risky links, test email attachments, and run different browsers without installing anything. It all runs in a sandbox, so your device stays safe, even when visiting sketchy sites or doing malware research.

    Who Uses Browserling?

    Browserling is trusted by developers, bug bounty hunters, cybersecurity researchers, and even major companies that need safe browsers. Teams at banks, governments, and tech firms use it for secure testing, but it’s just as useful for solo testers, students, or anyone who wants to explore the web without putting their device at risk. Whether you’re writing code, checking phishing emails, or analyzing shady links, it’s a tool that fits right in.

    Happy browsing!



    Source link

  • Online Tools Coupon Code (Summer 2025) ☀

    Online Tools Coupon Code (Summer 2025) ☀


    Brighten up your summer projects with Online Tools and my vast collection of utilities, perfect for all your image, text, and data editing needs!

    I’m excited to offer you an exclusive summer offer: use the coupon code SUNNYTOOLS25 at the checkout to get a special discount on my service.

    Don’t let the heat slow down your productivity. Stay ahead and stay efficient this sunny season with my quick and effective tools.

    PS. Today is the last day this coupon is valid.



    Source link

  • HTML Editor Online with Instant Preview and Zero Setup



    HTML Editor Online with Instant Preview and Zero Setup



    Source link

  • Write and Test Code Instantly With an Online Python Editor



    Write and Test Code Instantly With an Online Python Editor



    Source link

  • Online Signature Tools Now Have Neat Icons

    Online Signature Tools Now Have Neat Icons


    Last month, we added neat icons to Online JSON Tools, and today we have also added neat icons to Online Signature Tools. The new icons make it easier to find and use your favorite tools.

    What Are Online Signature Tools?

    Online Signature Tools, also known as Digital Signature Tools, are browser-based apps that help you edit and enhance your handwritten signature for digital use. They let you do things like remove the background, change the color, resize, rotate, and improve the quality of your scanned signature image. These tools are super useful for making your signature look clean and professional when signing PDFs, Word docs, or other digital documents.​

    What Are Online Signature Tool Synonyms?

    • E-signature tools
    • Digital signature makers
    • Online signing apps
    • Electronic signing software
    • Signature creator tools
    • Web signature generators
    • Digital signing tools
    • E-sign apps
    • Signature editor tools
    • Online signature generators
    • Digital signature software

    Who Created Online Signature Tools?

    Online Signature Tools were built by me and my team at Browserling. We wanted to create something simple and easy for people to use right in their browsers – no downloads, no installs, no complicated stuff. While we work on a bunch of handy online tools, we also do cross-browser testing to make sure everything works great no matter what browser you’re using. Our goal is to help regular users and developers save time and get things done without any tech headaches.

    Who Uses Online Signature Tools?

    Online Signature Tools and Browserling are used by everyone, including regular Internet users, freelancers, small business owners, and even Fortune 100 companies. They’re handy for signing documents, contracts, or forms quickly without printing or scanning. Everyday users use them for signing agreements or apartment leases, while professionals use them for signing NDAs and big contracts.

    Buy a subscription now at onlinePNGtools.com/pricing and use the coupon code SIGNLING for 30% off! 🤑



    Source link

  • Online Stamp Tools Now Have Neat Icons

    Online Stamp Tools Now Have Neat Icons


    Last month, we added neat icons to Online Icon Tools, and today we have also added neat icons to Online Stamp Tools (such as stamp background remover, stamp color changer, and stamp resizer) . The new icons make it easier to find and use your favorite tools.

    What Are Online Stamp Tools?

    Tools for editing stamps. Buy a subscription for full access.

    Who Created Online Stamp Tools?

    Team Browserling created Online Stamp Tools. Buy a subscription if you love us.

    Who Uses Online Stamp Tools?

    Everyone uses Online Stamp Tools. Buy a subscription to join the family.

    Buy a subscription now at onlinePNGtools.com/pricing and use the coupon code STAMPLING for 30% off! 🤑



    Source link

  • Online Icon Tools Now Have Neat Icons

    Online Icon Tools Now Have Neat Icons


    Last month, we added neat icons to Online Logo Tools, and today we have also added neat icons to Online Icon Tools. The new icons make it easier to find and use your favorite tools.

    What Are Online Icon Tools?

    Tools for editing icons. Buy a subscription for full access.

    Who Created Online Icon Tools?

    Team Browserling created Online Icon Tools. Buy a subscription if you love us.

    Who Uses Online Icon Tools?

    Everyone uses Online Icon Tools. Buy a subscription to join the family.

    Buy a subscription now at onlinePNGtools.com/pricing and use the coupon code ICONLING for 30% off! 🤑



    Source link