как я могу вернуть каталог, отраженный методом onchanged () в другом классе - PullRequest
0 голосов
/ 30 января 2019

Я много искал о захвате вырезать, скопировать событие в C #.Наконец, я решил поместить console.write () в метод onchanged (), чтобы показать путь к каталогу, на который влияют, путем вырезания, копирования действий, и, наконец, я хочу поймать консоль на месте ... Я определил метод (ochangepathgetter), которыйвозвращает (чистый путь, каталог затронутого каталога).Моя проблема в том, что я не могу перехватить эту переменную в другом классе?Может кто-нибудь изменить этот код, чтобы я мог захватить эту переменную?

using System;

using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

using System.Runtime.InteropServices;
using System.Threading;
using System.Data.SqlClient;

namespace Consoleapplication1
{
class program
{
    public int oc = 0;
    static void Main()
    {

        FileStream ostrm;
        StreamWriter writer;
        TextWriter oldOut = Console.Out;
        ostrm = new FileStream(@"D:\classic1\2.txt", FileMode.OpenOrCreate, FileAccess.Write);

        writer = new StreamWriter(ostrm);
        Console.SetOut(writer);
        watcher();
        Console.SetOut(oldOut);
        writer.Close();
        ostrm.Close();
        Console.Read();
    }
    public static void watcher()
    {
        DriveInfo[] alldrives = DriveInfo.GetDrives();
        foreach (DriveInfo drive in alldrives)
        {


            if (drive.Name.Contains('G'))
            //drive.name != delimon.win32.io.path.getpathroot(environment.Systemdirectory)
            {

                DirectoryInfo[] alldir = new DirectoryInfo(drive.Name).GetDirectories("*.*", SearchOption.AllDirectories);
                DirectoryInfo rootdir = new DirectoryInfo(drive.RootDirectory.Name);



                foreach (DirectoryInfo dir in alldir)
                {
                    FileSystemWatcher filewatcher = new FileSystemWatcher();
                    filewatcher.Path = dir.FullName;
                    filewatcher.Filter = "*.*";
                    filewatcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.Size;
                    filewatcher.Created += new FileSystemEventHandler(onchanged);
                    filewatcher.Deleted += new FileSystemEventHandler(onchanged);
                    filewatcher.Renamed += new RenamedEventHandler(onrenamed);
                    { filewatcher.EnableRaisingEvents = true; }




                }
                for (int i = 0; i < 1; i++)
                {
                    FileSystemWatcher filewatcher = new FileSystemWatcher();
                    filewatcher.Path = rootdir.FullName;
                    filewatcher.Filter = "*.*";
                    filewatcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.Size;
                    filewatcher.Created += new FileSystemEventHandler(onchanged);
                    filewatcher.Deleted += new FileSystemEventHandler(onchanged);
                    filewatcher.Renamed += new RenamedEventHandler(onrenamed);
                    { filewatcher.EnableRaisingEvents = true; }






                }



            }
        }

    }

    private static void onrenamed(object sender, RenamedEventArgs e)
    {
        Console.Write("the new name is " + e.Name + "and the old name was" + e.OldName);


    }

    private static void onchanged(object sender, FileSystemEventArgs e)
    {

        // Console.Write(e.FullPath);

        int index1 = e.FullPath.IndexOf(e.Name);
        string cleanpath = e.FullPath.Remove(index1, (e.FullPath.Length) - (index1));
        Console.Write(cleanpath);
        Console.Write(Environment.NewLine);
        ochangepathgetter(cleanpath);

    }
    public static long foldersize(string din)
    {
        //string dn = din.FullName.ToString();
        long leng = Directory.GetFiles(din, "*", SearchOption.AllDirectories).Sum(t => (new FileInfo(t).Length));
        return leng;
    }

    public static string ochangepathgetter(string path)
    {
        return path;
    }

}

}

1 Ответ

0 голосов
/ 30 января 2019

Если вы хотите сделать что-то в классе доступным для другого, одним из довольно простых вариантов будет поднять событие.Лично я бы реорганизовал ваш код, чтобы у вас был класс Watcher, который вызывает событие для cleanPath.Например (просто показаны наиболее важные части)

 class program
    {
        static void Main()
        {
            var watcher = new Watcher();
            watcher.Start();

            // hook into the event
            watcher.ChangedEvent += WatcherChanged;

            Console.Read();
        }

        private static void WatcherChanged(object sender, string e)
        {
            Console.WriteLine($"clean path is {e}");
        }
    }

    class Watcher
    {
        public EventHandler<string> ChangedEvent;

        public void Start()
        {
            DriveInfo[] alldrives = DriveInfo.GetDrives();
            // etc.
        }

        private void onchanged(object sender, FileSystemEventArgs e)
        {
            int index1 = e.FullPath.IndexOf(e.Name);
            string cleanpath = e.FullPath.Remove(index1, (e.FullPath.Length) - (index1));

            // fire the event
            if (this.ChangedEvent != null)
            {
                this.ChangedEvent(this, cleanpath);
            }
        }
...