Beispiel #1
0
        /**
         * static function to get list of folders on
         * the network name so provided
         */
        public static ArrayList get_folders(string server)
        {
            ArrayList folders = new ArrayList();

            if (server != null && server.Trim().Length > 0)
            {
                ShareCollection shi = ShareCollection.GetShares(server);
                if (shi != null)
                {
                    foreach (Share si in shi)
                    {
                        if (si.ShareType.ToString() == "Disk")
                        {
                            folders.Add(si.ToString());
                        }
                    }
                }
                else
                {
                    folders.Add("-1");
                    return(folders);
                }
            }
            return(folders);
        }
Beispiel #2
0
        public IList <IShare> GetShareList(List <String> toolNameList)
        {
            // using the solution from code-project (Richard Deeming)
            // https://www.codeproject.com/Articles/2939/Network-Shares-and-UNC-paths

            List <IShare> shareList = new List <IShare>();

            List <string> pcList = GetComputersListOnNetwork();

            if (pcList.Count == 0)
            {
                Logger?.InfoLog("The arrived computerlist is empty.", CLASS_NAME);
                return(shareList);
            }

            try
            {
                foreach (string pcName in pcList)
                {
                    // get list of shares on the PC
                    ShareCollection shareColl = ShareCollection.GetShares(pcName);

                    //get all files of each share:
                    foreach (Share sh in shareColl)
                    {
                        try
                        {
                            bool checkThekList = toolNameList.Any(p => sh.NetName.Contains(p));

                            if (sh.IsFileSystem && sh.ShareType == ShareType.Disk && checkThekList)
                            {
                                shareList.Add(new ShareAdapter(sh));
                            }
                        }
                        catch (Exception ex)
                        {
                            Logger?.ErrorLog($"Exception occured: {ex}", CLASS_NAME);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger?.ErrorLog($"Exception occured: {ex}", CLASS_NAME);
            }

            return(shareList);
        }
Beispiel #3
0
        void GetShares(string Host)
        {
            TreeNode        TNc = new TreeNode(Host);
            ShareCollection shi;

            TNc.Tag                = Host;
            TNc.ImageIndex         = 0;
            TNc.SelectedImageIndex = TNc.ImageIndex;
            int CurrIndex = 0;

            if (Host == "LocalHost")
            {
                shi = ShareCollection.LocalShares;
            }
            else
            {
                shi = ShareCollection.GetShares(Host);
            }
            if (shi != null)
            {
                foreach (Share si in shi)
                {
                    TreeNode TN = new TreeNode(si.NetName + "");
                    TN.Tag = si.ToString() + "";
                    if (si.ShareType == ShareType.Special)
                    {
                        TN.ImageIndex = 1;

                        TN.SelectedImageIndex = TN.ImageIndex;
                        TNc.Nodes.Insert(CurrIndex, TN);
                        CurrIndex += 1;
                    }
                    else
                    {
                        TN.ImageIndex         = 2;
                        TN.SelectedImageIndex = TN.ImageIndex;
                        TNc.Nodes.Add(TN);
                    }
                }
                TNc.Expand();
                treeView1.Nodes.Add(TNc);
                treeView1.TreeViewNodeSorter = new NodeSorter();
            }
        }
Beispiel #4
0
        private bool ValidatePath(string path)
        {
            try
            {
                if (Directory.Exists(path))
                {
                    return(true);
                }

                if (path.StartsWith("\\\\"))
                {
                    ShareCollection shares = ShareCollection.GetShares(path);
                    return(shares != null && shares.Count > 0);
                }
            }
            catch { }

            return(false);
        }
Beispiel #5
0
        public ArrayList GetNetworkShareFoldersList(string serverName)
        {
            ArrayList shares = new ArrayList();

            //Split each and go back one
            string[] parts = serverName.Split('\\');

            //Could not happend if stated as \\server\path\
            if (parts.Length < 3)
            {
                SetErrorString(@"GetNetworkShareFoldersList did not get a \\server\path as expected");
                return(shares);
            }

            string          server = @"\\" + parts[2] + @"\";
            ShareCollection shi    = ShareCollection.LocalShares;

            if (server != null && server.Trim().Length > 0)
            {
                shi = ShareCollection.GetShares(server);
                if (shi != null)
                {
                    foreach (Share si in shi)
                    {
                        //We only want the disks
                        if (si.ShareType == ShareType.Disk || si.ShareType == ShareType.Special)
                        {
                            DirectoryBrowse aDir = new DirectoryBrowse();
                            aDir.sPath = si.Root.FullName + @"\";
                            aDir.sName = si.NetName;
                            shares.Add(aDir);
                        }
                    }
                }
                else
                {
                    SetErrorString(@"Unable to enumerate the shares on " + server + " - Make sure the machine exists and that you have permission to access it");
                    return(new ArrayList());
                }
            }
            return(shares);
        }
Beispiel #6
0
        void RemoteShares(string ServerName)
        {
            ShareCollection shi = ShareCollection.GetShares(ServerName);

            if (shi != null)
            {
                foreach (Share si in shi)
                {
                    Console.WriteLine("{0}: {1} [{2}]",
                                      si.ShareType, si, si.Path);

                    // If this is a file-system share, try to
                    // list the first five subfolders.
                    // NB: If the share is on a removable device,
                    // you could get "Not ready" or "Access denied"
                    // exceptions.
                    // If you don't have permissions to the share,
                    // you will get security exceptions.
                    if (si.IsFileSystem)
                    {
                        try
                        {
                            System.IO.DirectoryInfo   d    = si.Root;
                            System.IO.DirectoryInfo[] Flds = d.GetDirectories();
                            for (int i = 0; i < Flds.Length && i < 5; i++)
                            {
                                Console.WriteLine("\t{0} - {1}", i, Flds[i].FullName);
                            }

                            Console.WriteLine();
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("\tError listing {0}:\n\t{1}\n",
                                              si.ToString(), ex.Message);
                        }
                    }
                }
            }
        }
Beispiel #7
0
        static int TestShares(string server)
        {
            ShareCollection shi;

            if (server != null && server.Trim().Length > 0)
            {
                shi = ShareCollection.GetShares(server);
                if (shi != null)
                {
                    foreach (Share si in shi)
                    {
                        if (si.IsFileSystem)
                        {
                            Console.WriteLine("{0}", si);
                        }
                    }
                }
                else
                {
                    return(-1);
                }
            }
            return(0);
        }
Beispiel #8
0
        /// <summary>
        /// Arbeitet einen FileServer ab
        /// </summary>
        /// <param name="server"></param>
        static void WorkOnFileServer(ConfigServer server)
        {
            // Liest die Shares des Servers aus
            ShareCollection shareColl = ShareCollection.GetShares(server.Name);

            // Wenn keine Shares gelesen werden konnten
            if (shareColl == null)
            {
                return;
            }

            int shareIndex = 1;

            // Schleife über jede ausgelesene Freigabe
            foreach (Share share in shareColl)
            {
                Log.write(shareIndex + "/" + shareColl.Count + " - " + share.NetName + " wird ausgelesen...", true, false);
                // Ruft alle Informationen ab und schreibt sie in die Datenbank
                FSWorker.GetSharesSecurity(share, server.DisplayName);

                Log.write(" fertig", false, true);
                shareIndex++;
            }
        }
        private void Explore(bool keepSelection)
        {
            if (InvokeRequired)
            {
                Invoke(new ExploreHandler(Explore), keepSelection);
                return;
            }

            List <string> selection = new List <string>();

            if (keepSelection)
            {
                selection.AddRange(SelectedPaths);
            }

            int selIdx = 0;

            try
            {
                selIdx = this.SelectedIndices[0];
            }
            catch
            {
                selIdx = 0;
            }

            lock (syncRoot)
            {
                try
                {
                    ignoreEvents = true;

                    bool isUncPathRoot = false;

                    CursorHelper.ShowWaitCursor(this, true);

                    // Check if current path is valid.
                    if (!Directory.Exists(m_strDirPath))
                    {
                        m_strDirPath = FindFirstUsablePath(m_strDirPath, ref isUncPathRoot);
                    }

                    AppConfig.LastExploredFolder = m_strDirPath;

                    if (!isUncPathRoot && PathUtils.IsRootPath(m_strDirPath))
                    {
                        m_strDirPath = m_strDirPath.TrimEnd(string.Copy(PathUtils.DirectorySeparator).ToCharArray()) + PathUtils.DirectorySeparator;
                    }

                    ShareCollection shares = null;
                    List <string>   dirs   = null;
                    List <string>   files  = null;

                    if (isUncPathRoot)
                    {
                        try
                        {
                            shares = ShareCollection.GetShares(m_strDirPath);
                        }
                        catch { }
                    }
                    else
                    {
                        try
                        {
                            dirs = PathUtils.EnumDirectories(m_strDirPath);
                        }
                        catch { }

                        try
                        {
                            files = PathUtils.EnumFilesUsingMultiFilter(m_strDirPath, this.SearchPattern);
                        }
                        catch { }
                    }

                    ClearCurrentContents();

                    CreateParentFolderRow();

                    if (isUncPathRoot && shares != null)
                    {
                        foreach (Share share in shares)
                        {
                            if (!share.IsFileSystem)
                            {
                                continue;
                            }

                            if (Directory.Exists(share.Root.FullName) == false)
                            {
                                continue;
                            }

                            CreateNewRow(share.Root.FullName);
                        }
                    }
                    else
                    {
                        if (dirs != null)
                        {
                            foreach (string dir in dirs)
                            {
                                if (Directory.Exists(dir) == false)
                                {
                                    continue;
                                }

                                CreateNewRow(dir);
                                int tt = 0;
                            }
                        }

                        if (files != null)
                        {
                            foreach (string file in files)
                            {
                                if (File.Exists(file) == false)
                                {
                                    continue;
                                }

                                CreateNewRow(file);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logger.LogException(ex);
                }
                finally
                {
                    CursorHelper.ShowWaitCursor(this, false);
                    ignoreEvents = true;
                }

                if (this.Items.Count <= 0)
                {
                    CreateMessageRow(string.Empty);
                    CreateMessageRow(Translator.Translate("TXT_FOLDERNOTACCESSIBLE"));
                }
            }

            this.Sort();

            //ClearSelection();
            this.SelectedItems.Clear();

            bool selectedSomething = false;

            if (keepSelection || _pathToSelect != null)
            {
                if ((selection != null && selection.Count > 0) || _pathToSelect != null)
                {
                    bool focusSet = false;

                    foreach (ListViewItem item in Items)
                    {
                        string path = item.Tag as string;
                        if (selection.Contains(path) || (string.Compare(_pathToSelect, path, true) == 0))
                        {
                            if (!focusSet)
                            {
                                item.Focused = true;
                                focusSet     = true;
                            }

                            item.Selected = true;
                            EnsureVisible(item.Index);
                            selectedSomething = true;
                        }
                    }
                }
            }
            else if (m_strPrevDirPath != null && m_strPrevDirPath.Length > 0)
            {
                int lastVisibleIndex = 0;
                foreach (ListViewItem item in this.Items)
                {
                    string path = item.Tag as string;
                    if (string.IsNullOrEmpty(path) == false)
                    {
                        item.Selected = false;

                        if (string.Compare(path, m_strPrevDirPath, false) == 0)
                        {
                            item.Selected = true;
                            item.Focused  = true;

                            lastVisibleIndex = item.Index;

                            break;
                        }
                    }
                }

                EnsureVisible(lastVisibleIndex);
                selectedSomething = true;
            }

            if (!selectedSomething)
            {
                if (selIdx < 0)
                {
                    selIdx = 0;
                }
                if (selIdx >= this.Items.Count)
                {
                    selIdx = this.Items.Count - 1;
                }

                this.Items[selIdx].Selected = true;
                this.Items[selIdx].Focused  = true;
                EnsureVisible(selIdx);
            }

            this.Select();
            this.Focus();
        }
Beispiel #10
0
    //static void Main(string[] args)
    //{
    //	TestShares();
    //}

    static void TestShares()
    {
        // Enumerate shares on local computer
        Console.WriteLine("\nShares on local computer:");
        ShareCollection shi = ShareCollection.LocalShares;

        if (shi != null)
        {
            foreach (Share si in shi)
            {
                Console.WriteLine("{0}: {1} [{2}]",
                                  si.ShareType, si, si.Path);

                // If this is a file-system share, try to
                // list the first five subfolders.
                // NB: If the share is on a removable device,
                // you could get "Not ready" or "Access denied"
                // exceptions.
                if (si.IsFileSystem)
                {
                    try
                    {
                        DirectoryInfo   d    = si.Root;
                        DirectoryInfo[] Flds = d.GetDirectories();
                        for (int i = 0; i < Flds.Length && i < 5; i++)
                        {
                            Console.WriteLine("\t{0} - {1}", i, Flds[i].FullName);
                        }

                        Console.WriteLine();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("\tError listing {0}:\n\t{1}\n",
                                          si, ex.Message);
                    }
                }
            }
        }
        else
        {
            Console.WriteLine("Unable to enumerate the local shares.");
        }

        Console.WriteLine();

        // Enumerate shares on a remote computer
        Console.Write("Enter the NetBios name of a server on your network: ");
        string server = Console.ReadLine();

        if (server != null && server.Trim().Length > 0)
        {
            Console.WriteLine("\nShares on {0}:", server);
            shi = ShareCollection.GetShares(server);
            if (shi != null)
            {
                foreach (Share si in shi)
                {
                    Console.WriteLine("{0}: {1} [{2}]", si.ShareType, si, si.Path);

                    // If this is a file-system share, try to
                    // list the first five subfolders.
                    // NB: If the share is on a removable device,
                    // you could get "Not ready" or "Access denied"
                    // exceptions.
                    // If you don't have permissions to the share,
                    // you will get security exceptions.
                    if (si.IsFileSystem)
                    {
                        try
                        {
                            System.IO.DirectoryInfo   d    = si.Root;
                            System.IO.DirectoryInfo[] Flds = d.GetDirectories();
                            for (int i = 0; i < Flds.Length && i < 5; i++)
                            {
                                Console.WriteLine("\t{0} - {1}", i, Flds[i].FullName);
                            }

                            Console.WriteLine();
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("\tError listing {0}:\n\t{1}\n",
                                              si.ToString(), ex.Message);
                        }
                    }
                }
            }
            else
            {
                Console.WriteLine("Unable to enumerate the shares on {0}.\n"
                                  + "Make sure the machine exists, and that you have permission to access it.",
                                  server);
            }

            Console.WriteLine();
        }

        // Resolve local paths to UNC paths.
        string fileName = string.Empty;

        do
        {
            Console.Write("Enter the path to a file, or \"Q\" to exit: ");
            fileName = Console.ReadLine();
            if (fileName != null && fileName.Length > 0)
            {
                if (fileName.ToUpper() == "Q")
                {
                    fileName = string.Empty;
                }
                else
                {
                    Console.WriteLine("{0} = {1}", fileName, ShareCollection.PathToUnc(fileName));
                }
            }
        } while (fileName != null && fileName.Length > 0);
    }
Beispiel #11
0
        /// <summary>
        /// Scan the client machine for services such as HTTP or samba shares
        /// </summary>
        /// <param name="n"></param>
        private void ScanClient(Node n)
        {
            //Check for HTTP
            string webTitle = string.Empty;

            try
            {
                var    wc   = new WebClient();
                string html = wc.DownloadString("http://" + n.Host);

                if (!string.IsNullOrEmpty(html))
                {
                    webTitle = RegexEx.FindMatches("<title>.*</title>", html).FirstOrDefault();
                    if (null != webTitle && !string.IsNullOrEmpty(html) && webTitle.Length > 14)
                    {
                        webTitle = webTitle.Substring(7);
                        webTitle = webTitle.Substring(0, webTitle.Length - 8);
                    }
                }

                if (string.IsNullOrEmpty(webTitle))
                {
                    webTitle = "Web";
                }
            }
            catch
            {
            }

            //Check for FTP
            string ftp = string.Empty;

            try
            {
                var client = new TcpClient();
                client.Connect(n.Host, 21);
                ftp = "FTP";
                var  sb    = new StringBuilder();
                long start = Environment.TickCount + 3000;
                var  data  = new byte[20000];
                client.ReceiveBufferSize = data.Length;

                while (start > Environment.TickCount && client.Connected)
                {
                    if (client.GetStream().DataAvailable)
                    {
                        int length = client.GetStream().Read(data, 0, data.Length);
                        sb.Append(Encoding.ASCII.GetString(data, 0, length));
                    }
                    else
                    {
                        Thread.Sleep(50);
                    }
                }
                client.Close();

                string title = sb.ToString();
                if (!string.IsNullOrEmpty(title))
                {
                    ftp = title;
                }
                data = null;
            }
            catch
            {
            }

            //Check for samba shares

            string samba = string.Empty;

            try
            {
                ShareCollection shares = ShareCollection.GetShares(n.Host);
                var             sb     = new StringBuilder();
                foreach (SambaShare share in shares)
                {
                    if (share.IsFileSystem && share.ShareType == ShareType.Disk)
                    {
                        try
                        {
                            //Make sure its readable
                            DirectoryInfo[] Flds = share.Root.GetDirectories();
                            if (sb.Length > 0)
                            {
                                sb.Append("|");
                            }
                            sb.Append(share.NetName);
                        }
                        catch
                        {
                        }
                    }
                }
                samba = sb.ToString();
            }
            catch
            {
            }

            lock (sync)
            {
                //update clients and overlords
                var r = new Node();
                r.SetData("HTTP", webTitle.Replace("\n", "").Replace("\r", ""));
                r.SetData("FTP", ftp.Replace("\n", "").Replace("\r", ""));
                r.SetData("Shares", samba.Replace("\n", "").Replace("\r", ""));
                r.ID         = n.ID;
                r.OverlordID = serverNode.ID;
                lock (sync)
                {
                    //Check the client is still connected..
                    if (connectedClientNodes.Where(nx => nx.Node.ID == r.ID).Count() > 0)
                    {
                        var verb = new UpdateVerb();
                        verb.Nodes.Add(r);
                        NetworkRequest req = verb.CreateRequest();
                        req.OverlordID = serverNode.ID;
                        SendToStandardClients(req);
                        //Dont updates about overlords to other overlords
                        if (n.NodeType != ClientType.Overlord)
                        {
                            SendToOverlordClients(req);
                        }
                    }
                }
                //Store info
                n.SetData("HTTP", webTitle.Replace("\n", "").Replace("\r", ""));
                n.SetData("FTP", ftp.Replace("\n", "").Replace("\r", ""));
                n.SetData("Shares", samba.Replace("\n", "").Replace("\r", ""));
            }
        }
Beispiel #12
0
        static void Main(string[] args)
        {
            string        checksumfile = new FileInfo(System.Reflection.Assembly.GetEntryAssembly().Location).Directory.FullName;
            string        output       = checksumfile + "\\Deletable_" + DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + ".txt";
            List <string> locations    = new List <string>();// ConfigurationManager.AppSettings.AllKeys.ToList();
            List <string> excludes     = ConfigurationManager.AppSettings["Exclude"].Split(';').ToList();

            excludes.RemoveAll(item => string.IsNullOrEmpty(item));
            ShareCollection shi;

            switch (Convert.ToBoolean(string.IsNullOrEmpty(ConfigurationManager.AppSettings["GetLocal"]) ? "false" : ConfigurationManager.AppSettings["GetLocal"]))
            {
            case true:
                shi = ShareCollection.LocalShares;
                break;

            case false:
            default:
                if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["NAS"]))
                {
                    shi = ShareCollection.GetShares(ConfigurationManager.AppSettings["NAS"]);
                }
                else
                {
                    Console.WriteLine("Invalid setting found in app.config, program terminated.");
                    return;
                }
                break;
            }
            if (shi != null)
            {
                foreach (Share si in shi)
                {
                    Console.WriteLine("{0}: {1} [{2}]",
                                      si.ShareType, si, si.Path);
                    if (si.ShareType == ShareType.Disk)
                    {
                        locations.Add(si.ToString().Replace(@"\\", @"\"));
                    }
                    // If this is a file-system share, try to
                    // list the first five subfolders.
                    // NB: If the share is on a removable device,
                    // you could get "Not ready" or "Access denied"
                    // exceptions.
                    //if (si.IsFileSystem)
                    //{
                    //    try
                    //    {
                    //        DirectoryInfo d = si.Root;
                    //        DirectoryInfo[] Flds = d.GetDirectories();
                    //        //for (int i = 0; i < Flds.Length && i < 5; i++)
                    //        //    Console.WriteLine("\t{0} - {1}", i, Flds[i].FullName);

                    //        //Console.WriteLine();
                    //    }
                    //    catch (Exception)
                    //    {
                    //        //Console.WriteLine("\tError listing {0}:\n\t{1}\n",
                    //        //    si, ex.Message);
                    //    }
                    //}
                }
            }
            else
            {
                Console.WriteLine("Unable to enumerate the local shares.");
            }


            //locations.Add(@"\\Diskstation\photo\");

            int           deletable = 0;
            List <string> FileList  = null;

            using (StreamWriter file = File.CreateText(output))
            { }
            foreach (var loc in locations)
            {
                Console.WriteLine("Scanning " + loc);
                FileList = GetFiles(loc, "*.*");
                if (FileList != null)
                {
                    if (FileList.Count != 0)
                    {
                        Console.WriteLine(FileList.Count + " files could be deleted by current user account");
                    }
                }
                if (FileList.Any())
                {
                    using (StreamWriter file = File.AppendText(output))
                    {
                        foreach (var fi in FileList)
                        {
                            file.WriteLine(fi);
                        }
                    }
                    deletable += FileList.Count;
                }
            }
            if (FileList != null)
            {
                Console.WriteLine("Total : " + deletable + " files could be deleted by current user account.");
            }
            Console.WriteLine("Finished");
            Console.ReadKey();
        }