Click here to Skip to main content
15,881,852 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi im trying to convert a file to a base64String and then store that string in a text file. What i am trying to create is a Windows Service - As soon as a file is created in a certain folder.The Service creates a Log file to say that a file has been added to the folder put then it should convert that file into a base64String and store that string in a text file.

EDIT 1:
Im trying to convert a file into a base64String.The code below successfully registers a new file being added to a folder. What im trying to do now is convert that file that has just been added to a base64String and store that string in a separate file. To code to convert to base64String is in the method ConvertToBase64(), That method is being called inside FileSystemWatcher1_Created(). What i have tried can be seen below
I Want to be able convert any file to a base64String that is added to certain folder
My Code

C#
using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Threading;
using System.Reflection;

namespace WindowsServiceFolderWatcher
{
    public partial class Service1 : ServiceBase
    {
        string WatchPath1 = ConfigurationManager.AppSettings["WatchPath1"];  
        public Service1()
        {
            InitializeComponent();
            fileSystemWatcher1.Created += fileSystemWatcher1_Created;
          

        }

        internal void TestStartupAndStop(string[] args)
        {
            this.OnStart(args);
            Console.ReadLine();
            this.OnStop();
        }
        FileSystemWatcher myWatcher = new FileSystemWatcher();
        protected override void OnStart(string[] args)
        {

            try
            {
                fileSystemWatcher1.Path = WatchPath1;

                
            }
            catch (Exception ex)
            {
                throw ex;
            }  
        }

        protected override void OnStop()
        {
            try
            {
                Create_ServiceStopTextFile();
            }
            catch (Exception ex)
            {

                throw ex;
            } 
        }
        void fileSystemWatcher1_Created(object sender, System.IO.FileSystemEventArgs e)
        {
            try
            {
                Thread.Sleep(7000);
                if(CheckFileExistance(WatchPath1, e.Name))
                {
                    CreateTextFile(WatchPath1, e.Name);
                    ConvertToBase64(/*WatchPath1, e.Name*/);
                   // Copy_Excelfile_And_Paste_at_anotherloaction_OnServiceStart(WatchPath1, e.Name);
                }
            }
            catch(Exception ex)
            {
                throw ex;
            }
        }
        
        private bool CheckFileExistance(string FullPath, string FileName)
        {
            // Get the subdirectories for the specified directory.'  
            bool IsFileExist = false;
            DirectoryInfo dir = new DirectoryInfo(FullPath);
            if (!dir.Exists)
                IsFileExist = false;
            else
            {
                string FileFullPath = Path.Combine(FullPath, FileName);
                if (File.Exists(FileFullPath))
                    IsFileExist = true;
            }
            return IsFileExist;


        }

        private void CreateTextFile(string FullPath, string FileName)
        {

            StreamWriter SW;

            if (!File.Exists(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "txtStatus_" + DateTime.Now.ToString("MMddyyyy") + ".txt")))
            {
                SW = File.CreateText(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "txtStatus_" + DateTime.Now.ToString("MMddyyyy") + ".txt"));
                //SW = File.CreateText(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "txtBase64_" + DateTime.Now.ToString("MMddyyyy") + ".txt"));
                SW.Close();
            }
            using (SW = File.AppendText(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "txtStatus_" + DateTime.Now.ToString("MMddyyyy") + ".txt")))
            {
                SW.WriteLine("File Created with Name: " + FileName + " at this time: " + DateTime.Now.ToString("HH:mm , MM/dd/yyyy"));
                // + FilePath
               
                SW.Close();
            }

           // Copy_Excelfile_And_Paste_at_anotherloaction_OnServiceStart();
        
        }

        public static void ConvertToBase64(/*string FullPath, string FileName*/)
        {

            //First Attempt
            //string tiff = FullPath;
            //FileStream fstream = new FileStream(tiff, FileMode.Open);
            //byte[] original = new byte[fstream.Length];
            //fstream.Read(original, 0, (int)fstream.Length);
            //int fstreamLength = (int)fstream.Length;
            //string tiffBase64 = Convert.ToBase64String(original);

            //StreamWriter writer = new StreamWriter(@"C:\\Users\\username\\Desktop\\Base64\\SampleBase64.txt");
            //writer.Write(tiffBase64);
            //writer.Close();
            //fstream.Close();

            //Second Attempt
            using (System.IO.Stream s = new System.IO.FileStream(@"C:\\Users\\username\\Desktop\\Ball.jpg", System.IO.FileMode.Open, System.IO.FileAccess.Read))
            {
                var bytes = StreamHelper.ReadToEnd(s);

                var string64 = Convert.ToBase64String(bytes);

                //Console.WriteLine(/*"Size " +*/ string64);
                File.WriteAllBytes(@"C:\\Users\\username\\Desktop\\Base64\\Base.txt", Convert.FromBase64String(string64));
                //var bytes2 = Convert.FromBase64String(string64);
                //bytes.WriteAllBytes(@"C:\Users\username\Desktop\output24.pdf", bytes2);

               

            }


        

        }

        public static void Create_ServiceStopTextFile()
        {
            string Destination = "C:\\Users\\username\\Desktop\\FileWatcherWinService";
            StreamWriter SW;
            if (Directory.Exists(Destination))
            {
                Destination = System.IO.Path.Combine(Destination, "txtServiceStop_" + DateTime.Now.ToString("yyyyMMdd") + ".txt");
                if (!File.Exists(Destination))
                {
                    SW = File.CreateText(Destination);
                    SW.Close();
                }
            }
            using (SW = File.AppendText(Destination))
            {
                SW.Write("\r\n\n");
                SW.WriteLine("Service Stopped at: " + DateTime.Now.ToString("dd-MM-yyyy H:mm:ss"));
                SW.Close();
            }

        }

        public static void Copy_Excelfile_And_Paste_at_anotherloaction_OnServiceStart()
        {
            try
            {
                string source = "C:\\Users\\username\\Desktop\\Documents";
                string Destination = "C:\\Users\\username\\Desktop\\Destination";
                string filename = string.Empty;
                if (!(Directory.Exists(Destination) && Directory.Exists(source)))
                    return;
                string[] Templateexcelfile = Directory.GetFiles(source);
                foreach (string file in Templateexcelfile)
                {
                    if (file.Contains("Excel"))
                    {
                        filename = System.IO.Path.GetFileName(file);
                        Destination = System.IO.Path.Combine(Destination, filename.Replace(".xlsx", DateTime.Now.ToString("yyyyMMdd")) + ".xlsx");
                        System.IO.File.Copy(file, Destination, true);
                    }
                }

            }
            catch (Exception ex)
            {
                Create_ServiceStopTextFile();
            }

        }
        internal void DebugMode()
        {
            this.OnStart(null);
        }
    }
}


What I have tried:

C#
  //First Attempt
            //string tiff = FullPath;
            //FileStream fstream = new FileStream(tiff, FileMode.Open);
            //byte[] original = new byte[fstream.Length];
            //fstream.Read(original, 0, (int)fstream.Length);
            //int fstreamLength = (int)fstream.Length;
            //string tiffBase64 = Convert.ToBase64String(original);

            //StreamWriter writer = new StreamWriter(@"C:\\Users\\username\\Desktop\\Base64\\SampleBase64.txt");
            //writer.Write(tiffBase64);
            //writer.Close();
            //fstream.Close();

//Second Attempt
            using (System.IO.Stream s = new System.IO.FileStream(@"C:\\Users\\username\\Desktop\\Ball.jpg", System.IO.FileMode.Open, System.IO.FileAccess.Read))
            {
                var bytes = StreamHelper.ReadToEnd(s);

                var string64 = Convert.ToBase64String(bytes);

                //Console.WriteLine(/*"Size " +*/ string64);
                File.WriteAllBytes(@"C:\\Users\\username\\Desktop\\Base64\\Base.txt", Convert.FromBase64String(string64));
                //var bytes2 = Convert.FromBase64String(string64);
                //bytes.WriteAllBytes(@"C:\Users\username\Desktop\output24.pdf", bytes2);

               

            }
Posted
Updated 13-Jun-16 6:31am
v3
Comments
F-ES Sitecore 13-Jun-16 11:48am    
What's the question?
BEBE2011 13-Jun-16 12:14pm    
edited my question
OriginalGriff 13-Jun-16 11:48am    
And?
What is the problem?
Where are you stuck?
What help do you need?
Use the "Improve question" widget to edit your question and provide better information.
BEBE2011 13-Jun-16 12:14pm    
edited my question
OriginalGriff 13-Jun-16 12:16pm    
That doesn't explain what your problem is: it's just a statement of what you want to end up with!
How much of it have you done? Where are you stuck?

1 solution

"I'am stuck at the part where the newly created file is converted to a base64String. Previously i created an application that took a hardcoded file and turned it into a base64String. im trying to to the same but with any file now."
All you have to do is replace the hardcoded path with the FileSystemEventArgs.FullPath Property (System.IO)[^] you are handed in the fileSystemWatcher1_Created event handler when the event is fired!
Assuming your service has the appropriate access permissions on the folder (and it may not by default, it doesn't run under your user account) it should work.
 
Share this answer
 
Comments
Matt T Heffron 13-Jun-16 14:15pm    
I've just been reading about FileSystemWatcher, and it appears that the Created event happens when the file is first opened for writing. Don't you have to wait for the size or last write time to stop changing (Changed event) for some time (application specific) to know when the file is finished being written and Closed?
OriginalGriff 13-Jun-16 14:29pm    
Either that or loop retrying the StreamReader.
Good point. Depends on the application writing the file to a huge extent.
I always tend to think of the file as logically being created when the writer is closed, but I know that's wrong and didn't consider it here.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900