Share via


PDF to Base64 using c#

Question

Tuesday, October 29, 2019 1:49 AM

I  have a folder where there will be .docx, .png, .pdf , .txt files places.

There will be UniqueId value sent from Web service.

The fileNames in the folder are same as UniqueId values (for .docx, .png, .pdf , .txt files).

How to convert the documents to base64 ? Please advise

RH

All replies (28)

Tuesday, October 29, 2019 2:01 AM

Hello Dan2890,

From your post I believe you have a folder with files and a service that will return the files based on a given id. Your question is how to return the files as a byte[].

If I am correct then you could use File.ReadAllBytes() to get the content as a byte[] regardless of the type of document it is.

Cheers, Jeff


Tuesday, October 29, 2019 2:17 AM

Actually there will be a folder with all type of Attachments (.pdf, .png, .txt, .docx) in it with FileNames as UniqueId values. Depend on what I receive the UniqueId value, I need to pick the Attachment convert to base64 as a string and assign this value to another field

RH


Tuesday, October 29, 2019 2:19 AM

great; so the File.ReadAllBytes() should work in that case.

Cheers, Jeff


Tuesday, October 29, 2019 2:26 AM

Can you please provide me the code for this like just the method and logic ?

RH


Tuesday, October 29, 2019 3:09 AM

how about:

byte[] GetFileContentByName(string id)
{
    var file = Directory.GetFiles("c:\\temp", $"{id}.*").FirstOrDefault();
    if(file != null)
       return File.ReadAllBytes(file);    return null;
}

Cheers, Jeff


Wednesday, October 30, 2019 1:19 AM

c:\\temp
var file = Directory.GetFiles("c:\\temp", $"{id}.*").FirstOrDefault();

Can we make the folder location path directory dynamic ? I mean here it is static value c:\temp ?

RH


Wednesday, October 30, 2019 1:23 AM

of course. it can be a setting from the configuration file, a parameter passed in, a value read from a database, or ?

The method signature would change to have a parameter passed in:

byte[] GetFileContentByName(string path, string id)
{
    var file = Directory.GetFiles(path, $"{id}.*").FirstOrDefault();
    if(file != null)
       return File.ReadAllBytes(file);
    return null;
}

Cheers, Jeff


Wednesday, October 30, 2019 1:36 AM

Well the below method is returning data Type as byte right ?

public byte[] GetFileContentByName(string path, string id)
{
    var file = Directory.GetFiles(path, $"{id}.*").FirstOrDefault();
    if(file != null)
       return System.Convert.ToBase64String(File.ReadAllByes(file))
    return null;
}

But I want return type as Base64String. How can I update my code ?

RH


Wednesday, October 30, 2019 1:37 AM

byte[] - an array of byte

Cheers, Jeff


Wednesday, October 30, 2019 1:39 AM

I modified my code, is this correct ?

public byte[] GetFileContentByName(string path, string id)
{
    var file = Directory.GetFiles(path, $"{id}.*").FirstOrDefault();
    if(file != null)
       return System.Convert.ToBase64String(File.ReadAllByes(file))
    return null;
}

RH


Wednesday, October 30, 2019 1:43 AM

if you want to do that then you need to change the return type:

public string GetFileContentByName(string path, string id)
{
    var file = Directory.GetFiles(path, $"{id}.*").FirstOrDefault();
    if (file != null)
        return System.Convert.ToBase64String(File.ReadAllBytes(file));

    return null;
}

Cheers, Jeff


Wednesday, October 30, 2019 2:36 AM

Hi Dan,

Thank you for posting here.

According to your description, it seems that you want to convert more than one document into Base64String.

If so, you can try the following code to get it.

        static void Main(string[] args)
        {
            String path = @"d:\test";
            List<String> base64Strings = GetBase64Strings(path, 1);

            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
        }

        static List<String> GetBase64Strings(String path,int UniqueId)
        {
            List<String> base64Strings = new List<String>();
            var files = Directory.GetFiles(path, $"{UniqueId}.*");
            if (files.Length != 0)
            {
                foreach (var filePath in files)
                {
                    Byte[] bytes = File.ReadAllBytes(filePath);
                    String base64String = Convert.ToBase64String(bytes);
                    base64Strings.Add(base64String);
                }
            }
            return base64Strings;
        }

Hope my solution could be helpful.

Best regards,

Timon

MSDN Community Support
Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact [email protected].


Friday, November 8, 2019 9:45 PM

Thanks Timon.

I have a concern, say I have 3 files Attachments A1.pdf, B1.xml, C1.txt

They will be placed in the folder prepended with UniqueId like :

UniqueIdA1.pdf

UniqueIdB1.xml

UniqueIdC1.txt

So when I am using above logic, it doesnt pick any Attachment files.

I need to fix the logic where it says Files contains UniqueId : How can I update the code ?

Thank you in advance

var files = Directory.GetFiles(path, $"{UniqueId}.*");

RH


Monday, November 11, 2019 9:19 AM

Hi Dan,

Thanks for you feedback.

Do you mean that the folder is named by the UniqueId?

If so, the file path should look like this:

d:\test\1\B.xml

d:\test\1\C.txt

You can try the following code to get it.

        static List<String> GetBase64Strings(String path, int UniqueId)
        {
            List<String> base64Strings = new List<String>();
            var files = Directory.GetFiles(path+"\\"+$"{UniqueId}", $"*.*");
            if (files.Length != 0)
            {
                foreach (var filePath in files)
                {
                    Console.WriteLine(filePath);
                    Byte[] bytes = File.ReadAllBytes(filePath);
                    String base64String = Convert.ToBase64String(bytes);
                    base64Strings.Add(base64String);
                    Console.WriteLine(base64String);
                }
            }
            return base64Strings;
        } 

Hope this could be helpful.

Best Regards,

Timon

MSDN Community Support
Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact [email protected].


Monday, November 11, 2019 3:59 PM

well I need to Loop through each matching Attachment, and one at a time create and send the payload

well if there are multiple attachments then how do I return one at a time  ?

For e.g : 

UniqueId1A1.pdf

UniqueId1B1.png

UniqueId1C1.docx.

My requirement is, when the cursor matches and reads the first file, **UniqueId1A1.pdf ** it needs to return back as a string.

Only after then it needs to read UniqueId1B1.png attachment, covert to string and return.

And then so on....

Is this possible ?

RH


Tuesday, November 12, 2019 9:48 AM

Hi Dan,

Thanks for your feedback.

The following code can be implemented to return a string each time, you can do something on the returned string and then get the string of the next file.

        static void Main(string[] args)
        {
            String path = @"d:\test";
            int UniqueId = 1;
            var files = Directory.GetFiles(path + "\\" + $"{UniqueId}", "*.*");
            foreach (var filePath in files)
            {
                Console.WriteLine($"This file is:{filePath}, read it?(Y | N)");
                string input = Console.ReadLine();
                if (input.Equals("Y"))
                {
                    string base64String = GetBase64String(filePath);
                //Do something.
                    Console.WriteLine(base64String);
                }
                else if(input.Equals("N"))
                {
                    break;    
                }
            }
            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
        }

        static String GetBase64String(String path)
        {
            Byte[] bytes = File.ReadAllBytes(path);
            String base64String = Convert.ToBase64String(bytes);

            return base64String;
        }

You can also use the Winform program to do this, which will looks more elegant.

But the idea is the same.

Hope this could be helpful.

Best Regards,

Timon

MSDN Community Support
Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact [email protected].


Tuesday, November 12, 2019 10:04 PM

Thanks Timon.

How can I return List of files ?

Because the above string is returning only 1 string.

I will be receiving array , so I wanted to returnList of files ?

RH


Wednesday, November 13, 2019 8:28 AM

Hi Dan,

Thanks for your feedback.

I modified the code according to your requirements.

        static void Main(string[] args)
        {
            String path = @"d:\test";
            int UniqueId = 1;
            List<string> base64Strings = GetBase64Strings(path, UniqueId);

            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
        }

        static List<string> GetBase64Strings(String path, int UniqueId)
        {
            List<string> base64Strings = new List<string>();
            var files = Directory.GetFiles(path + "\\" + $"{UniqueId}", $"*.*");
            if (files.Length != 0)
            {
                foreach (var filePath in files)
                {
                    Console.WriteLine($"This file is:{filePath}, read it?(Y | N)");
                    string input = Console.ReadLine();
                    if (input.Equals("Y"))
                    {
                        Byte[] bytes = File.ReadAllBytes(filePath);
                        String base64String = Convert.ToBase64String(bytes);
                        //Do something.
                        Console.WriteLine(base64String);
                        base64Strings.Add(base64String);
                    }
                    else if (input.Equals("N"))
                    {
                        break;
                    }
                }
            }
            return base64Strings;
        }

Hope this could be helpful.

Best Regards,

Timon

MSDN Community Support
Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact [email protected].


Wednesday, November 13, 2019 9:49 PM

When I run the above method, it throws error.

1.Cannot find part of the file , it is not able to find anything after the UniqueId

 var files = Directory.GetFiles(path + $"{UniqueId}", $"*.*");

2. Is there another method I can create to just get all the complete file Names containing the Unique Id ?

RH


Thursday, November 14, 2019 1:05 AM

Hi Dan,

Could you provide the full path of the files to me?

I need this information to write the code that suits you.

Best regards,

Timon

MSDN Community Support
Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact [email protected].


Thursday, November 14, 2019 1:32 AM

Path Location : C:\ProjectName\SourceFolder\

FileNames :

UniqueId1MNOPQRST.pdf

UniqueId1ZYHPD.xml

UniqueId1LLLLL.txt

UniqueId2LWDJKIJD.png

UniqueId3KKKJK.pdf

UniqueId3uhdjn.docx

The above code you provided can read upto SourceFolder\UniqueId but it is not able to read the content after UniqueId1 and so on... Not able to find MNOPQRST from the file name. Hope I am making sense now.

RH


Thursday, November 14, 2019 2:36 AM

Hi Dan,

Thanks for your feedback.

I modified the code and it should be fine this time.

       static void Main(string[] args)
        {
            String path = @"d:\test";
            int UniqueId = 1;
            List<string> base64Strings = GetBase64Strings(path, UniqueId);

            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
        }

        static List<string> GetBase64Strings(String path, int UniqueId)
        {
            List<string> base64Strings = new List<string>();

            DirectoryInfo objDirectoryInfo = new DirectoryInfo(path);
            FileInfo[] files = objDirectoryInfo.GetFiles("*.*", SearchOption.TopDirectoryOnly);

            string regex = $"^{UniqueId}.*$";
            foreach (var file in files)
            {
                if (Regex.IsMatch(file.Name,regex))
                {
                    Console.WriteLine($"This file is:{file}, read it?(Y | N)");
                    string input = Console.ReadLine();
                    if (input.Equals("Y"))
                    {
                        Byte[] bytes = File.ReadAllBytes(file.FullName);
                        String base64String = Convert.ToBase64String(bytes);
                        //Do something.
                        Console.WriteLine(base64String);
                        base64Strings.Add(base64String);
                    }
                    else if (input.Equals("N"))
                    {
                        break;
                    }
                }
            }
            return base64Strings;
        }

There are 4 files in my folder.

If the Uniqueld is 1, the program can read 1B.xml and 1C.txt.

Hope this could be helpful.

Best Regards,

Timon

MSDN Community Support
Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact [email protected].


Thursday, November 14, 2019 2:42 AM

I will check this out.

In the meantime, can I write another method which returns all file Names (complete file name) which contains UniqueId passed ?

RH


Thursday, November 14, 2019 2:52 AM

Hi Dan,

This is the method to return the files name.

        static List<string> GetFilesName(String path, int UniqueId)
        {
            List<string> filesName = new List<string>();
            DirectoryInfo objDirectoryInfo = new DirectoryInfo(path);
            FileInfo[] files = objDirectoryInfo.GetFiles("*.*", SearchOption.TopDirectoryOnly);
            string regex = $"^{UniqueId}.*$";
            foreach (var file in files)
            {
                if (Regex.IsMatch(file.Name, regex))
                {
                    //File Name.
                    string fileName = file.Name;
                    //Full name(Including path).
                    string fileFullName = file.FullName;

                    filesName.Add(fileName);
                }
            }
            return filesName;
        }

Best Regards,

Timon

MSDN Community Support
Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact [email protected].


Thursday, November 14, 2019 2:56 AM

Can you please share me your email ? 

I can explain you my scenario in detail, may be I can share my project with you that may clearly help for you to understand what my requirement is please ?

RH


Thursday, November 14, 2019 3:10 AM

Hi Dan,

I'm afraid I can't.
This violates our safety guidelines.
If there are other problems in your project, you can create a new thread and describe the problem in detail. We will reply you as soon as possible.

Best Regards, 

Timon

MSDN Community Support
Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact [email protected].


Friday, November 15, 2019 12:58 AM

Hi Chilberto,

I think the logic you provided will work in my scenario, but the issue I am facing is it is picking files only with 'id' filenames.

I will be receiving file names which are concatenated along with id and extension.

For e.g : ID123.pdf, ID499.docx, ID909ABC.png...

 Please advise how can I modify this existing code ?

public string GetFileContentByName(string path, string id)
{
    var file = Directory.GetFiles(path, $"{id}.*").FirstOrDefault();
    if (file != null)
        return System.Convert.ToBase64String(File.ReadAllBytes(file));

    return null;
}

RH


Friday, November 15, 2019 9:16 PM

Come on, Dan.  You have to do some of this work yourself.  You just need to think about what information you HAVE, and what information you NEED.  I believe you want that function to accept one file name, and return one base64 string.  If so, then you don't really want to call Directory.GetFiles here.  The function is being handed the name.  Right?

So, the code that calls this will need to be inside a loop.  That code will find the files, and pass the file names one by one into the function.  For example,

    foreach( string name in Directory.GetFiles(path,"ID*") )
    {
       string b64 = GetFileContentByName(name);
        // Do something with b64
    }

 

Tim Roberts | Driver MVP Emeritus | Providenza & Boekelheide, Inc.