Share via

I test to save file in string sourceDir = @"C:\Users\sy\Documents\"; it working but if user save that file to difference directory , how to detect?

MIPAKTEH_1 605 Reputation points
2024-12-22T13:56:48.1366667+00:00
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Delete_a
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            // Initialize FileSystemWatcher
            FileSystemWatcher watcher = new FileSystemWatcher(@"c:\\")
            {
                NotifyFilter = NotifyFilters.Attributes
                    | NotifyFilters.CreationTime
                    | NotifyFilters.DirectoryName
                    | NotifyFilters.FileName
                    | NotifyFilters.LastWrite
                    | NotifyFilters.Size,
                Filter = "*.*",  // Monitor all file types
                IncludeSubdirectories = true,
                EnableRaisingEvents = true
            };
            // Hook into events
            watcher.Created += OnCreated;

            Console.WriteLine("Press enter to exit.");
            Console.ReadLine();
        }

        void OnCreated(object sender, FileSystemEventArgs e)
        {
            string sourceDir = @"C:\Users\sy\Documents\";
            string TargetPath = @"C:\Users\sy\Documents\test22";
            try
            {
                FileInfo fileInfo = new FileInfo(e.FullPath);
                var targetFile = Path.Combine(TargetPath, fileInfo.Name);

                string[] txtList = Directory.GetFiles(sourceDir, "*.*");

                foreach (string file in txtList)
                {
                    if (Ready(file) == true)
                    {
                        File.Delete(file);
                    }
                }
                string value = $"Created: {e.FullPath}";
                listBox1.Invoke(new Action(() => listBox1.Items.Add(value)));
            }
            catch (Exception exception)
            {
                Debug.WriteLine(exception.Message);
            }
        }
        private static void DisplayException(Exception ex)
        {
            if (ex == null) return;
            Debug.WriteLine($"Message: {ex.Message}");
            Debug.WriteLine("Stack trace:");
            Debug.WriteLine(ex.StackTrace);
            Debug.WriteLine("");
            DisplayException(ex.InnerException);
        }
        public static bool Ready(string filename)
        {
            try
            {
                using (FileStream inputStream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.None))
                    return inputStream.Length > 0;
            }
            catch (Exception)
            {
                return false;
            }
        }

    }
}

Developer technologies | C#
Developer technologies | C#

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.

0 comments No comments

Answer accepted by question author

Anonymous
2024-12-23T03:15:15.07+00:00

Hi @MIPAKTEH_1 , Welcome to Microsoft Q&A,

You cannot enforce restrictions at the OS level directly from your application.

If your application allows saving files, you can restrict it to a specific directory.

string sourceDir = @"C:\Users\sy\Documents\";
SaveFileDialog saveDialog = new SaveFileDialog
{
    InitialDirectory = sourceDir,
    Filter = "All Files|*.*",
    RestoreDirectory = true
};

if (saveDialog.ShowDialog() == DialogResult.OK)
{
    string savePath = saveDialog.FileName;
    if (!savePath.StartsWith(sourceDir, StringComparison.OrdinalIgnoreCase))
    {
        MessageBox.Show("You can only save files to the designated directory.");
        return;
    }

    // Save file logic
    File.WriteAllText(savePath, "Your file content here");
}

Best Regards,

Jiale


If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". 

Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

Was this answer helpful?

0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.