Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

c# check either work or not service on a remote computer

 
using System.Management;

       static bool ServiceIsRunning(string ServiceName)
        {
            ConnectionOptions op = new ConnectionOptions();
            op.Username = "domain\\username";
            op.Password = "password";
            ManagementScope scope = new ManagementScope("\\\\OLAP1\\root\\cimv2", op);
            scope.Connect();

            string objPath = string.Format("Win32_Service.Name='{0}'", "SubscribeReportService");
            using (ManagementObject service = new ManagementObject(scope, new ManagementPath(objPath), null))
            {
                if (service.GetPropertyValue("State").ToString() == "Running")
                    return true;
                else
                    return false;
            }
        }

http://stackoverflow.com/questions/1335065/check-status-of-services-that-run-in-a-remote-computer-using-c-sharp

Accessing a Shared File (UNC) From a Remote, Non-Trusted Domain With Credentials

 
using System;
using System.Runtime.InteropServices;
using System.ComponentModel;

namespace YourNameSpace
{
    /// 
    /// Provides access to a network share.
    /// 
    public class NetworkShareAccesser : IDisposable
    {
        private string _remoteUncName;
        private string _remoteComputerName;

        public string RemoteComputerName
        {
            get
            {
                return this._remoteComputerName;
            }
            set
            {
                this._remoteComputerName = value;
                this._remoteUncName = @"\\" + this._remoteComputerName;
            }
        }

        public string UserName
        {
            get;
            set;
        }
        public string Password
        {
            get;
            set;
        }

        #region Consts

        private const int RESOURCE_CONNECTED = 0x00000001;
        private const int RESOURCE_GLOBALNET = 0x00000002;
        private const int RESOURCE_REMEMBERED = 0x00000003;

        private const int RESOURCETYPE_ANY = 0x00000000;
        private const int RESOURCETYPE_DISK = 0x00000001;
        private const int RESOURCETYPE_PRINT = 0x00000002;

        private const int RESOURCEDISPLAYTYPE_GENERIC = 0x00000000;
        private const int RESOURCEDISPLAYTYPE_DOMAIN = 0x00000001;
        private const int RESOURCEDISPLAYTYPE_SERVER = 0x00000002;
        private const int RESOURCEDISPLAYTYPE_SHARE = 0x00000003;
        private const int RESOURCEDISPLAYTYPE_FILE = 0x00000004;
        private const int RESOURCEDISPLAYTYPE_GROUP = 0x00000005;

        private const int RESOURCEUSAGE_CONNECTABLE = 0x00000001;
        private const int RESOURCEUSAGE_CONTAINER = 0x00000002;


        private const int CONNECT_INTERACTIVE = 0x00000008;
        private const int CONNECT_PROMPT = 0x00000010;
        private const int CONNECT_REDIRECT = 0x00000080;
        private const int CONNECT_UPDATE_PROFILE = 0x00000001;
        private const int CONNECT_COMMANDLINE = 0x00000800;
        private const int CONNECT_CMD_SAVECRED = 0x00001000;

        private const int CONNECT_LOCALDRIVE = 0x00000100;

        #endregion

        #region Errors

        private const int NO_ERROR = 0;

        private const int ERROR_ACCESS_DENIED = 5;
        private const int ERROR_ALREADY_ASSIGNED = 85;
        private const int ERROR_BAD_DEVICE = 1200;
        private const int ERROR_BAD_NET_NAME = 67;
        private const int ERROR_BAD_PROVIDER = 1204;
        private const int ERROR_CANCELLED = 1223;
        private const int ERROR_EXTENDED_ERROR = 1208;
        private const int ERROR_INVALID_ADDRESS = 487;
        private const int ERROR_INVALID_PARAMETER = 87;
        private const int ERROR_INVALID_PASSWORD = 1216;
        private const int ERROR_MORE_DATA = 234;
        private const int ERROR_NO_MORE_ITEMS = 259;
        private const int ERROR_NO_NET_OR_BAD_PATH = 1203;
        private const int ERROR_NO_NETWORK = 1222;

        private const int ERROR_BAD_PROFILE = 1206;
        private const int ERROR_CANNOT_OPEN_PROFILE = 1205;
        private const int ERROR_DEVICE_IN_USE = 2404;
        private const int ERROR_NOT_CONNECTED = 2250;
        private const int ERROR_OPEN_FILES = 2401;

        #endregion

        #region PInvoke Signatures

        [DllImport("Mpr.dll")]
        private static extern int WNetUseConnection(
            IntPtr hwndOwner,
            NETRESOURCE lpNetResource,
            string lpPassword,
            string lpUserID,
            int dwFlags,
            string lpAccessName,
            string lpBufferSize,
            string lpResult
            );

        [DllImport("Mpr.dll")]
        private static extern int WNetCancelConnection2(
            string lpName,
            int dwFlags,
            bool fForce
            );

        [StructLayout(LayoutKind.Sequential)]
        private class NETRESOURCE
        {
            public int dwScope = 0;
            public int dwType = 0;
            public int dwDisplayType = 0;
            public int dwUsage = 0;
            public string lpLocalName = "";
            public string lpRemoteName = "";
            public string lpComment = "";
            public string lpProvider = "";
        }

        #endregion

        /// 
        /// Creates a NetworkShareAccesser for the given computer name. The user will be promted to enter credentials
        /// 
        /// 
        /// 
        public static NetworkShareAccesser Access(string remoteComputerName)
        {
            return new NetworkShareAccesser(remoteComputerName);
        }

        /// 
        /// Creates a NetworkShareAccesser for the given computer name using the given domain/computer name, username and password
        /// 
        /// 
        /// 
        /// 
        /// 
        public static NetworkShareAccesser Access(string remoteComputerName, string domainOrComuterName, string userName, string password)
        {
            return new NetworkShareAccesser(remoteComputerName,
                                            domainOrComuterName + @"\" + userName,
                                            password);
        }

        /// 
        /// Creates a NetworkShareAccesser for the given computer name using the given username (format: domainOrComputername\Username) and password
        /// 
        /// 
        /// 
        /// 
        public static NetworkShareAccesser Access(string remoteComputerName, string userName, string password)
        {
            return new NetworkShareAccesser(remoteComputerName,
                                            userName,
                                            password);
        }

        private NetworkShareAccesser(string remoteComputerName)
        {
            RemoteComputerName = remoteComputerName;

            this.ConnectToShare(this._remoteUncName, null, null, true);
        }

        private NetworkShareAccesser(string remoteComputerName, string userName, string password)
        {
            RemoteComputerName = remoteComputerName;
            UserName = userName;
            Password = password;

            this.ConnectToShare(this._remoteUncName, this.UserName, this.Password, false);
        }

        private void ConnectToShare(string remoteUnc, string username, string password, bool promptUser)
        {
            NETRESOURCE nr = new NETRESOURCE
            {
                dwType = RESOURCETYPE_DISK,
                lpRemoteName = remoteUnc
            };

            int result;
            if (promptUser)
            {
                result = WNetUseConnection(IntPtr.Zero, nr, "", "", CONNECT_INTERACTIVE | CONNECT_PROMPT, null, null, null);
            }
            else
            {
                result = WNetUseConnection(IntPtr.Zero, nr, password, username, 0, null, null, null);
            }

            if (result != NO_ERROR)
            {
                throw new Win32Exception(result);
            }
        }

        private void DisconnectFromShare(string remoteUnc)
        {
            int result = WNetCancelConnection2(remoteUnc, CONNECT_UPDATE_PROFILE, false);
            if (result != NO_ERROR)
            {
                throw new Win32Exception(result);
            }
        }

        /// 
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// 
        /// 2
        public void Dispose()
        {
            this.DisconnectFromShare(this._remoteUncName);
        }
    }
}

using
 
                        using (NetworkShareAccesser.Access(server, Config.Domain, Config.User, Config.Pass))
                        {

                            return System.IO.File.ReadAllText(res.path);
                        }

c# Create custom exception

  public class CertNotValidException : Exception
    {
        public CertNotValidException()
            : base() { }
 
        public CertNotValidException(string message)
            : base(message) { }
 
        public CertNotValidException(string format, params object[] args)
            : base(string.Format(format, args)) { }
 
        public CertNotValidException(string message, Exception innerException)
            : base(message, innerException) { }
 
        public CertNotValidException(string format, Exception innerException, params object[] args)
            : base(string.Format(format, args), innerException) { }
    }

c# RunProcedure with logging

    string RunProc(string s,Func<string,string> _a)
        {
            try
            {
                return _a.Invoke(s);
            }
            catch (Exception e)
            {
                var msg = e.Message;
                if (e.InnerException != null)
                    msg = msg + e.InnerException.Message + e.StackTrace;
                msg = msg + "||InString:" + s;
                Common.WriteLog(DateTime.Now.ToString() + ":" + msg);
                return msg;
            }
        }
            return RunProc(s,(x) =>
            {
                return "success";
            });

C# Задаем прокси с логин паролем ( Credentials) для .NET приложения

Этот способ пробовал,работает точно


WebProxy wproxy = new WebProxy("new proxy",true);
wproxy.Credentials = new NetworkCredential("user", "pass");

WebRequest.DefaultWebProxy = wproxy;
И в конфиг

  <system.net>
    <defaultProxy
      useDefaultCredentials="true" >
    </defaultProxy>
  </system.net>

Ниже способ не пробовал но по виду должен работать

Create an assembly called SomeAssembly.dll with this class :
namespace SomeNameSpace
{
    public class MyProxy : IWebProxy
    {
        public ICredentials Credentials
        {
            get { return new NetworkCredential("user", "password"); }
            //or get { return new NetworkCredential("user", "password","domain"); }
            set { }
        }

        public Uri GetProxy(Uri destination)
        {
            return new Uri("http://my.proxy:8080");
        }

        public bool IsBypassed(Uri host)
        {
            return false;
        }
    }
}

Add this to your config file :
<defaultProxy enabled="true" useDefaultCredentials="false">
  <module type = "SomeNameSpace.MyProxy, SomeAssembly" />
</defaultProxy>

C# Скачать файл

bool DownLoadFile()
{
  WebClient myWebClient = new WebClient();
  myWebClient.DownloadFile("http://e-trust.gosuslugi.ru/CA/DownloadTSL?schemaVersion=0", @"c:\temp\ListOfCA.xml");
  return true;
}


///с Proxy
        public static bool DownLoadFile()
        {
            WebProxy wproxy = new WebProxy("10.10.0.2:8080", true);
            wproxy.Credentials = new NetworkCredential("int", "FSinet1234","fsrar");

            WebClient myWebClient = new WebClient();
            myWebClient.Proxy = wproxy;
            myWebClient.DownloadFile("http://e-trust.gosuslugi.ru/CA/DownloadTSL?schemaVersion=0", @"\\iis2\certs\ListOfCA.xml");
            
            return true;
        }

C# How to work with Excel. Simple example.


using Excel = Microsoft.Office.Interop.Excel; 
        
void CreateExcel()
        {
            Excel.Application xlApp;
            Excel.Workbook xlWorkBook;
            Excel.Worksheet xlWorkSheet;
            object misValue = System.Reflection.Missing.Value;

            xlApp = new Excel.Application();//new Excel.ApplicationClass();
            xlWorkBook = xlApp.Workbooks.Add(misValue);

            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);


            int i = 3;
            int j = 0;
            xlWorkSheet.Cells[1, 1] = "Protocol from " + DateTime.Now.ToShortDateString();
            Excel.Range rg = (Excel.Range)xlWorkSheet.Cells[1, 1];
            rg.EntireColumn.NumberFormat = "MM/DD/YYYY";

            xlWorkSheet.Columns.AutoFit();
                
            xlWorkBook.SaveAs("sdfgsdfg.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, Excel.XlSaveConflictResolution.xlLocalSessionChanges, misValue, misValue, misValue, misValue);
            xlWorkBook.Close(true, misValue, misValue);
            xlApp.Quit();

            releaseObject(xlWorkSheet);
            releaseObject(xlWorkBook);
            releaseObject(xlApp);
        }

        private void releaseObject(object obj)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
            }
            catch (Exception ex)
            {
                obj = null;
            }
            finally
            {
                GC.Collect();
            }
        }

c# Перехватываем любое окно в Windows и вводим в него текст или прячем

Передаем какой то текст в окно,как будто вводим с клавиатуры и жмем ОК кнопкой Enter:
int iHandle = Common.NativeWin32.FindWindow(null, "Сюда пишем заголовок нужного окна");
Common.NativeWin32.SetForegroundWindow(iHandle);
System.Windows.Forms.SendKeys.SendWait("Здесь пишем текст который нужно ввести в это окно");
//Жмем в окне Enter   
System.Windows.Forms.SendKeys.SendWait("{ENTER}");

По аналогии прячем окно:
int iHandle = Common.NativeWin32.FindWindow(null, "Заголовок окна");
Common.NativeWin32.SetWindowPos(new IntPtr(iHandle), Common.NativeWin32.HWND.Top, 0, 0, 0, 0, Common.NativeWin32.SetWindowPosFlags.AsynchronousWindowPosition);

Вспомогательный класс:
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace DeclTerminalApp.Common
{
    class NativeWin32
    {
        public const int WM_SYSCOMMAND = 0x0112;
        public const int SC_CLOSE = 0xF060;

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, SetWindowPosFlags uFlags);

        static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
        static readonly IntPtr HWND_NOTOPMOST = new IntPtr(-2);
        static readonly IntPtr HWND_TOP = new IntPtr(0);
        static readonly IntPtr HWND_BOTTOM = new IntPtr(1);

        /// <summary>
        /// Window handles (HWND) used for hWndInsertAfter
        /// </summary>
        public static class HWND
        {
            public static IntPtr
            NoTopMost = new IntPtr(-2),
            TopMost = new IntPtr(-1),
            Top = new IntPtr(0),
            Bottom = new IntPtr(1);
        }

        /// <summary>
        /// SetWindowPos Flags
        /// </summary>
        public static class SWP
        {
            public static readonly int
            NOSIZE = 0x0001,
            NOMOVE = 0x0002,
            NOZORDER = 0x0004,
            NOREDRAW = 0x0008,
            NOACTIVATE = 0x0010,
            DRAWFRAME = 0x0020,
            FRAMECHANGED = 0x0020,
            SHOWWINDOW = 0x0040,
            HIDEWINDOW = 0x0080,
            NOCOPYBITS = 0x0100,
            NOOWNERZORDER = 0x0200,
            NOREPOSITION = 0x0200,
            NOSENDCHANGING = 0x0400,
            DEFERERASE = 0x2000,
            ASYNCWINDOWPOS = 0x4000;
        }

        [Flags()]
        public enum SetWindowPosFlags : uint
        {
            /// <summary>If the calling thread and the thread that owns the window are attached to different input queues, 
            /// the system posts the request to the thread that owns the window. This prevents the calling thread from 
            /// blocking its execution while other threads process the request.</summary>
            /// <remarks>SWP_ASYNCWINDOWPOS</remarks>
            AsynchronousWindowPosition = 0x4000,
            /// <summary>Prevents generation of the WM_SYNCPAINT message.</summary>
            /// <remarks>SWP_DEFERERASE</remarks>
            DeferErase = 0x2000,
            /// <summary>Draws a frame (defined in the window's class description) around the window.</summary>
            /// <remarks>SWP_DRAWFRAME</remarks>
            DrawFrame = 0x0020,
            /// <summary>Applies new frame styles set using the SetWindowLong function. Sends a WM_NCCALCSIZE message to 
            /// the window, even if the window's size is not being changed. If this flag is not specified, WM_NCCALCSIZE 
            /// is sent only when the window's size is being changed.</summary>
            /// <remarks>SWP_FRAMECHANGED</remarks>
            FrameChanged = 0x0020,
            /// <summary>Hides the window.</summary>
            /// <remarks>SWP_HIDEWINDOW</remarks>
            HideWindow = 0x0080,
            /// <summary>Does not activate the window. If this flag is not set, the window is activated and moved to the 
            /// top of either the topmost or non-topmost group (depending on the setting of the hWndInsertAfter 
            /// parameter).</summary>
            /// <remarks>SWP_NOACTIVATE</remarks>
            DoNotActivate = 0x0010,
            /// <summary>Discards the entire contents of the client area. If this flag is not specified, the valid 
            /// contents of the client area are saved and copied back into the client area after the window is sized or 
            /// repositioned.</summary>
            /// <remarks>SWP_NOCOPYBITS</remarks>
            DoNotCopyBits = 0x0100,
            /// <summary>Retains the current position (ignores X and Y parameters).</summary>
            /// <remarks>SWP_NOMOVE</remarks>
            IgnoreMove = 0x0002,
            /// <summary>Does not change the owner window's position in the Z order.</summary>
            /// <remarks>SWP_NOOWNERZORDER</remarks>
            DoNotChangeOwnerZOrder = 0x0200,
            /// <summary>Does not redraw changes. If this flag is set, no repainting of any kind occurs. This applies to 
            /// the client area, the nonclient area (including the title bar and scroll bars), and any part of the parent 
            /// window uncovered as a result of the window being moved. When this flag is set, the application must 
            /// explicitly invalidate or redraw any parts of the window and parent window that need redrawing.</summary>
            /// <remarks>SWP_NOREDRAW</remarks>
            DoNotRedraw = 0x0008,
            /// <summary>Same as the SWP_NOOWNERZORDER flag.</summary>
            /// <remarks>SWP_NOREPOSITION</remarks>
            DoNotReposition = 0x0200,
            /// <summary>Prevents the window from receiving the WM_WINDOWPOSCHANGING message.</summary>
            /// <remarks>SWP_NOSENDCHANGING</remarks>
            DoNotSendChangingEvent = 0x0400,
            /// <summary>Retains the current size (ignores the cx and cy parameters).</summary>
            /// <remarks>SWP_NOSIZE</remarks>
            IgnoreResize = 0x0001,
            /// <summary>Retains the current Z order (ignores the hWndInsertAfter parameter).</summary>
            /// <remarks>SWP_NOZORDER</remarks>
            IgnoreZOrder = 0x0004,
            /// <summary>Displays the window.</summary>
            /// <remarks>SWP_SHOWWINDOW</remarks>
            ShowWindow = 0x0040,
        }

        [DllImport("user32.dll")]
        public static extern int FindWindow(
            string lpClassName, // class name 
            string lpWindowName // window name 
        );

        [DllImport("user32.dll")]
        public static extern int SendMessage(
            int hWnd, // handle to destination window 
            uint Msg, // message 
            int wParam, // first message parameter 
            int lParam // second message parameter 
        );

        [DllImport("user32.dll")]
        public static extern int SetForegroundWindow(
            int hWnd // handle to window
            );

        private const int GWL_EXSTYLE = (-20);
        private const int WS_EX_TOOLWINDOW = 0x80;
        private const int WS_EX_APPWINDOW = 0x40000;
              
        public const int GW_HWNDFIRST = 0;
        public const int GW_HWNDLAST  = 1;
        public const int GW_HWNDNEXT  = 2;
        public const int GW_HWNDPREV  = 3;
        public const int GW_OWNER     = 4;
        public const int GW_CHILD     = 5;

        public delegate int EnumWindowsProcDelegate(int hWnd, int lParam);

        [DllImport("user32")]
        public static extern int EnumWindows(EnumWindowsProcDelegate lpEnumFunc, int lParam);

        [DllImport("User32.Dll")]
        public static extern void GetWindowText(int h, StringBuilder s, int nMaxCount);

        [DllImport("user32", EntryPoint = "GetWindowLongA")]
        public static extern int GetWindowLongPtr(int hwnd, int nIndex);

        [DllImport("user32")]
        public static extern int GetParent(int hwnd);

        [DllImport("user32")]
        public static extern int GetWindow(int hwnd, int wCmd);

        [DllImport("user32")]
        public static extern int IsWindowVisible(int hwnd);

        [DllImport("user32")]
        public static extern int GetDesktopWindow();
    }
}

c# Вставляем флэшку в компьютер и обрабатываем это событие


Thread t = new Thread(Flashwatcher);
t.Start();

//...
        private void Flashwatcher()
        {
            ManagementScope scope = new ManagementScope("root\\CIMV2");
            scope.Options.EnablePrivileges = true;
            
            
            WqlEventQuery query = new WqlEventQuery();
            query.EventClassName = "__InstanceCreationEvent";
            query.WithinInterval = new TimeSpan(0, 0, 1);
            query.Condition = @"TargetInstance ISA 'Win32_USBControllerdevice'";
            watcher = new ManagementEventWatcher(scope, query);
            watcher.Start();
            watcher.WaitForNextEvent();
        }

c# парсим строку текст


public List<string> ParseString(string _string4Parse,string _beginVal,string _endVal)
        {
            List<string> res = new List<string>();
            int _begin = 0;
            while ((_begin = _string4Parse.IndexOf(_beginVal, _begin)) > -1)
            {
                _begin += _beginVal.Length;
                int _length = _string4Parse.IndexOf(_endVal, _begin)-_begin;
                res.Add(_string4Parse.Substring(_begin, _length));
            }
            return res;
        }

c# read rss


using System;
using System.Collections.Generic;
using System.Xml;
using System.ServiceModel.Syndication;

namespace LJUpper
{
    public static class RSS
    {
        public struct RssItem
        {
            public string Title { get; set; }
            public string Text { get; set; }
        }

        public static List<RssItem> GetRSS(string _feedUri)
        {
            SyndicationFeed syndicationFeed;
            List<RssItem> resList = new List<RssItem>();
            try
            {
                using (XmlReader reader = XmlReader.Create(new Uri(_feedUri).AbsoluteUri))
                    syndicationFeed = SyndicationFeed.Load(reader);

                string _title = "";
                string _text = "";


                foreach (SyndicationItem t in syndicationFeed.Items)
                {
                    if (t.Title == null)
                        _title += t.Title.Text;
                    if (t.Content == null)
                        _text += t.Summary.Text;
                    else
                        _text += (t.Content as TextSyndicationContent).Text;
                    resList.Add(new RssItem() { Title = t.Title.Text, Text = _text });
                }
            }
            catch
            {
                return null;
            }
            return resList;
        }
    }
}

c# проверка email

public static bool checkEmailString(string val)
        {
            if (val.Trim() != "")
            {
                System.Text.RegularExpressions.Match rex = 
                    System.Text.RegularExpressions.Regex.Match(val.Trim(),
                    "^([0-9a-zA-Z]([-.\\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\\w]*[0-9a-zA-Z]\\.)+[a-zA-Z]{2,3})$", 
                    System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                if (!rex.Success)
                    return false;
                else
                    return true;
            }
            else
                return false;
        }

c# Проверка состоит ли из чисел строка

public static bool isDigit(string val)
        {
            foreach (char c in val)
                if (!Char.IsDigit(c))
                    return false;
            return true;
        }

C# Get the version of your solution in Visual Studio

string s1 = Application.ProductVersion; //Only product version
string s2 = System.Reflection.Assembly.GetExecutingAssembly().FullName; // Returns Project1, Version=1.0.2281.26155, Culture=neutral, PubliKeyToken=null

c# получить хэш файла / c# get hash from file

public static string GetMD5HashFromFile(string fileName)
        {
            FileStream file = new FileStream(fileName, FileMode.Open);
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] retVal = md5.ComputeHash(file);
            file.Close();

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < retVal.Length; i++)
            {
                sb.Append(retVal[i].ToString("x2"));
            }
            return sb.ToString();
        }

c# читаем последнюю строку и удаляем её / Get last line from file and delete it

private static string ReadDeleteHashFromFile(string MyFilePath)
{
            string lastline = "";
            using (StreamReader reader = new StreamReader(dumpFilePath))
            {
                using (StreamWriter writer = new StreamWriter("myfile.tmp"))
                {
                    string line = reader.ReadLine();
                    
                    while (!reader.EndOfStream)
                    {
                        writer.Write(line);
                        line = reader.ReadLine();
                        if (!reader.EndOfStream)
                            writer.Write(writer.NewLine);
                    }
                    lastline = line;
                }
            }
            File.Delete(MyFilePath);
            File.Move("myfile.tmp", MyFilePath);
            File.Delete("myfile.tmp");
            return lastline;
}

c# add a line to the end of a file

using (StreamWriter sw = new StreamWriter(dumpFilePath, true, Encoding.ASCII))
            {
                string s="My new line";
                sw.WriteLine();
                sw.Write(s);
                sw.Close();
            }