unrestrict only picture files on a certain local path or network path

unrestrict only picture files on a certain local path or network path
using System.IO.IsolatedStorage of .NET
picture file types such as .jpg .bmp .gif .pcx

Any ideas how to use it properly to get the whole scenario.


thanks
LVL 14
systanAsked:
Who is Participating?
 
Meir RivkinConnect With a Mentor Full stack Software EngineerCommented:
IsolatedStorage has no built in functionality which restrict specific file types.
what you should do is encapsulate IsolatedStorage via IsolatedStorageManager wrapper class which upon insert validate the source extension.
 
public class IsolatedStorageManager : IDisposable
    {
        readonly string _topLevelDirectory;
        readonly string _extension;
        IsolatedStorageFile _isoStore = null;
        static IsolatedStorageManager _Instance = new IsolatedStorageManager();

        public static IsolatedStorageManager Instance
        {
            get
            {
                return _Instance;
            }
        }

        public IsolatedStorageManager()
        {
            _topLevelDirectory = ConfigurationManager.AppSettings["topLevelDirectory"];
            _extension = ConfigurationManager.AppSettings["ext"];
            _isoStore = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Domain | IsolatedStorageScope.Assembly, null, null);
            _isoStore.CreateDirectory(_topLevelDirectory);
        }

        public bool Store(string fileName, string data)
        {
            bool stored = false;
            if (Path.GetExtension(fileName).Equals(_extension, StringComparison.CurrentCultureIgnoreCase))
            {
                using (IsolatedStorageFileStream isoStream1 = new IsolatedStorageFileStream(fileName, FileMode.Create, _isoStore))
                {
                    isoStream1.Write(Encoding.ASCII.GetBytes(data), 0, data.Length);
                }
                stored = true;
            }
            else
            {
                Console.WriteLine("Invalid file type, expect {0}", _extension);
            }
            return stored;
        }

        public string ReadAll(string fileName)
        {
            using (IsolatedStorageFileStream isoStream1 = new IsolatedStorageFileStream(fileName, FileMode.Open, _isoStore))
            {
                byte[] bytes = new byte[isoStream1.Length];
                int numBytesToRead = (int)isoStream1.Length;
                int numBytesRead = 0;
                while (numBytesToRead > 0)
                {
                    int n = isoStream1.Read(bytes, numBytesRead, numBytesToRead);

                    if (n == 0)
                        break;

                    numBytesRead += n;
                    numBytesToRead -= n;
                }
                numBytesToRead = bytes.Length;
                return Encoding.ASCII.GetString(bytes);
            }
        }

        public bool Delete(string fileName)
        {
            try
            {
                _isoStore.DeleteFile(fileName);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return false;
            }
            return true;
        }

        #region IDisposable Members

        public void Dispose()
        {
            try
            {
                _isoStore.DeleteDirectory(_topLevelDirectory);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        #endregion
    }

    class Program
    {
        static void Main(string[] args)
        {
            bool res = IsolatedStorageManager.Instance.Store("meir.txt", "1234");
            string data = IsolatedStorageManager.Instance.ReadAll("meir.txt");
            res = IsolatedStorageManager.Instance.Delete("meir.txt");
            data = IsolatedStorageManager.Instance.ReadAll("meir.txt");
        }
    }

Open in new window

0
 
systanAuthor Commented:
Ok;
in other words;  
Allow writing of image files to a specific path only;
sample; to;
c:\my_pictures_only\
or
\\my_pictures_\_network_path_only\


thanks for that link, I'll try to visit now.
0
Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

 
systanAuthor Commented:
sindhuxyz;
I think your links are not relevant for a solution
0
 
systanAuthor Commented:
Does that code, prevents a file from creating if the path is not right?
or
it only looks if the file is created on the right path, but if not?, delete the file?
>>_isoStore.DeleteFile(fileName); ?
0
 
Meir RivkinFull stack Software EngineerCommented:
it only validates the extension of the file
0
 
systanAuthor Commented:
Ahm, does that validate before a file creation is made? or I guess after?
0
 
systanAuthor Commented:
Man,
I think System.IO.IsolatedStorage can't detect file BEFORE creation.

I have this link, BUT I'm not sure if this is applicable to my needs.
http://www.codeproject.com/KB/files/FileSystemWatcherChaos1.aspx


Example Output that I want;
When user paste an image file<.jpg>  to drive [d]
it will ask or a messagebox appear;
--------------
Creating a file on Drive [d]?, Do you really want to paste the file<.jpg>?  [yes] or [no]
--------------
0
 
systanAuthor Commented:
sedgwick?
0
 
Meir RivkinFull stack Software EngineerCommented:
this a different requirement from the question u posted, i'll try to help you anyway.
so you need some kind of mechanism to hook copying/moving files to some restrict folder.
check this sample from msdn:
http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.filter.aspx

this is exactly what u need, you can detect any copy/move/rename of file to/from your designated folder and popup dialog or whatever u need to do prior the action.
0
 
systanAuthor Commented:
>>to hook copying ?
you meant to hook pasting? or renaming it?


thanks
0
 
Meir RivkinFull stack Software EngineerCommented:
all of them, if you look at the code the event handler catch all actions done to this folder:
copy file to it, move to it, rename file, rename folder etc.
0
 
systanAuthor Commented:
Ok; I think;
WatcherChangeTypes.Created
is all I need, but do you think before creation of file a prompt message of yes or no is possible?
like;
Example Output that I want;
When user paste an image file<.jpg>  to drive [d]
it will ask or a messagebox appear;
--------------
Creating a file on Drive [d]?, Do you really want to paste the file<.jpg>?  [yes] or [no]
--------------
0
 
systanAuthor Commented:
>>all of them?
Ohm, but I hope BEFORE a file is created, not after.
0
 
systanAuthor Commented:
WatcherChangeTypes.Created is AFTER
WaitForChanged is BEFORE?
I'm really confused.
0
 
Meir RivkinFull stack Software EngineerCommented:
every time new file (only jpeg files) is created or copied or moved into this folder, a mesage box will popup to ask if you want to perform this action...
public static void Main()
        {
            Run();

        }

        [System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
        public static void Run()
        {
            string[] args = System.Environment.GetCommandLineArgs();

            // Create a new FileSystemWatcher and set its properties.
            FileSystemWatcher watcher = new FileSystemWatcher();
            watcher.Path = @"c:\temp";
            /* Watch for changes in LastAccess and LastWrite times, and
               the renaming of files or directories. */
            watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
               | NotifyFilters.FileName | NotifyFilters.DirectoryName;
            // Only watch text files.
            watcher.Filter = "*.jpeg";

            // Add event handlers.
            watcher.Created += new FileSystemEventHandler(watcher_Created);

            // Begin watching.
            watcher.EnableRaisingEvents = true;

            // Wait for the user to quit the program.
            Console.WriteLine("Press \'q\' to quit the sample.");
            while (Console.Read() != 'q') ;
        }

        static void watcher_Created(object sender, FileSystemEventArgs e)
        {
            if (MessageBox.Show(string.Format("Do you really want to paste the file {0}?", e.FullPath), "", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question) != DialogResult.Yes)
            {
                File.Delete(e.FullPath);
            }
        }

Open in new window

0
 
Meir RivkinFull stack Software EngineerCommented:
change the folder path (currently it's c:\temp) on line 14
0
 
systanAuthor Commented:
Man, I don't have a vs right now, but I'm surprised.

static void watcher_Created(object sender, FileSystemEventArgs e)
        {
            if (MessageBox.Show(string.Format("Do you really want to paste the file {0}?", e.FullPath), "", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question) != DialogResult.Yes)
            {
                File.Delete(e.FullPath);
            }
        }

Do you really think that will work
?


even if I will assigned the path to < \\sharedTemp\ > or  < d:\ >
?

I'm really surprised with the post, after a lot of searches.



thank you, I've change the points, in-case you didn't noticed.
0
 
Meir RivkinFull stack Software EngineerCommented:
10x alot man
0
 
systanAuthor Commented:
Ok; I got vs now; What's the alternative of MessageBox.Show?
my framework is 2 only

MessageBoxButtons.is for .net 4

What's my alternative to test the code directly?
0
 
systanAuthor Commented:
>>man?
lol, Sorry, I'm over exited of what you did.
0
 
Meir RivkinFull stack Software EngineerCommented:
Console.WriteLine or log to a file
0
 
systanAuthor Commented:
Ok; I got it, added reference, windows.forms;

I've noticed this; Why we have to issue a delete command?
>> File.Delete(e.FullPath);


I've noticed also the messagebox prompts AFTER the file was created,  so it doesn't do the job to restrict an image file creation.


I though it was.
0
 
systanAuthor Commented:
sedgwick;
http://msdn.microsoft.com/en-us/library/cc144063%28v=VS.85%29.aspx

That is the solution for folders, but not with files, can you help me in file operations.



thanks
0
 
Meir RivkinFull stack Software EngineerCommented:
FileWatcher is for files, did u test the code?
0
 
systanAuthor Commented:
Yes, the problem is, it does notify when the file is already created, that's after method.
I'm seeking for a method BEFORE a file is created.
Just like this code output;

Example Output that I want;
When user paste an image file<.jpg>  to drive [d]
it will ask or a messagebox appear;
--------------
Creating a file on Drive [d]?, Do you really want to CONTINUE paste/create the file<.jpg>?  [yes] or [no]
--------------


FileWatcher is also an AFTER creation
0
 
Meir RivkinFull stack Software EngineerCommented:
that's true, thats why the code has the File.Delete function.
0
 
systanAuthor Commented:
Ok;
it's not preventing a group of image files to be copied.

A file delete solution is not good, for me.

Ok, I would really like to close this post, but I am not really satisfied with the answers.

One last try; for connected question;
How do I list the files currently copied in the clipboard?
by that procedure, I can remove in the list,  a group of image files with an extension of .jpg?

I just need a link to close this; please

thank you
0
 
systanAuthor Commented:
http://msdn.microsoft.com/en-us/library/c2thcsx4.aspx
I have that code, but I'm not sure how to remove a group of image files from the file clipboard.
Can you do the test for me?

I hope by that procedure, I can remove in the list,  a group of image files with an extension of .jpg

So, when the user copies a lot of files, including image files like .jpg, when user paste the file?, .jpg image files will not be pasted.
' Demonstrates SetFileDropList, ContainsFileDroList, and GetFileDropList
Public Function SwapClipboardFileDropList(ByVal replacementList _
    As System.Collections.Specialized.StringCollection) _
    As System.Collections.Specialized.StringCollection

    Dim returnList As System.Collections.Specialized.StringCollection _
        = Nothing

    If Clipboard.ContainsFileDropList() Then

        returnList = Clipboard.GetFileDropList()
        Clipboard.SetFileDropList(replacementList)
    End If

    Return returnList

End Function

Open in new window

0
 
Meir RivkinFull stack Software EngineerCommented:
to use this function:
RemoveImageFilesFromClipboard(new string[] { ".jpeg", ".jpg", ".bmp", ".tiff" });
public static void RemoveImageFilesFromClipboard(string[] types)
        {
            StringCollection sc = Clipboard.GetFileDropList();
            StringCollection scNew = new StringCollection();
            scNew.AddRange(sc.Cast<string>().Where(n => !types.Contains(Path.GetExtension(n))).ToArray());
            Clipboard.SetFileDropList(scNew);
        }

Open in new window

0
 
systanAuthor Commented:
Ok;
Great
But I don't know why this line error's
scNew.AddRange(sc.Cast<string>().Where(n => !types.Contains(Path.GetExtension(n))).ToArray());

Error      1      Invalid expression term '>'      D:\My Documents\Visual Studio 2005\Projects\WindowsApplication2\WindowsApplication2\Form1.cs      24      55      WindowsApplication2
Error      2      ) expected      D:\My Documents\Visual Studio 2005\Projects\WindowsApplication2\WindowsApplication2\Form1.cs      24      57      WindowsApplication2
Error      3      ; expected      D:\My Documents\Visual Studio 2005\Projects\WindowsApplication2\WindowsApplication2\Form1.cs      24      94      WindowsApplication2
Error      4      Invalid expression term ')'      D:\My Documents\Visual Studio 2005\Projects\WindowsApplication2\WindowsApplication2\Form1.cs      24      94      WindowsApplication2
Error      5      ; expected      D:\My Documents\Visual Studio 2005\Projects\WindowsApplication2\WindowsApplication2\Form1.cs      24      105      WindowsApplication2
Error      6      Invalid expression term ')'      D:\My Documents\Visual Studio 2005\Projects\WindowsApplication2\WindowsApplication2\Form1.cs      24      105      WindowsApplication2

Ok, if we get this done?,    do I need to make a Timer for this?,   so every time users copy a group of files with image file, they can't paste it.
0
 
systanAuthor Commented:
Oh, StringCollection is not good with .NET 2.0
0
 
systanAuthor Commented:
Ok;
I added;
using System.Collections.Specialized;

But still errors; on;
scNew.AddRange(sc.Cast<string>().Where(n = !types.Contains(Path.GetExtension(n))).ToArray());

lines;...............
Error      1      'System.Collections.Specialized.StringCollection' does not contain a definition for 'Cast'      D:\My Documents\Visual Studio 2005\Projects\WindowsApplication2\WindowsApplication2\Form1.cs      29      31      WindowsApplication2
Error      2      The name 'n' does not exist in the current context      D:\My Documents\Visual Studio 2005\Projects\WindowsApplication2\WindowsApplication2\Form1.cs      29      52      WindowsApplication2
Error      3      'System.Array' does not contain a definition for 'Contains'      D:\My Documents\Visual Studio 2005\Projects\WindowsApplication2\WindowsApplication2\Form1.cs      29      63      WindowsApplication2
Error      4      The name 'Path' does not exist in the current context      D:\My Documents\Visual Studio 2005\Projects\WindowsApplication2\WindowsApplication2\Form1.cs      29      72      WindowsApplication2
Error      5      The name 'n' does not exist in the current context      D:\My Documents\Visual Studio 2005\Projects\WindowsApplication2\WindowsApplication2\Form1.cs      29      90      WindowsApplication2


What's the problem?
0
 
systanAuthor Commented:
Ok, got it working;
BUT, it doesn't follow your function <RemoveImageFilesFromClipboard>

public static void RemoveImageFilesFromClipboard(string[] ListFilePaths)
        {
            StringCollection sc = Clipboard.GetFileDropList();
            StringCollection scNew = new StringCollection();

            //scNew.AddRange(sc.().Where(ListFilePaths = !Types.Contains(System.IO.Path.GetExtension(n))).ToArray());
            //scNew.AddRange(sc.Cast<string>().Where(ListFilePaths = !ListFilePaths.Contains(Path.GetExtension(n))).ToArray());
            //Clipboard.SetFileDropList(scNew);

            foreach (string FileToCopy in sc)
                {
                    /// individually cast, not good using or and or
                    if (FileToCopy.Contains(".jpg")) { }
                    else
                        scNew.Add(FileToCopy);
                }
            scNew.Add("c:\\file.test");
            Clipboard.SetFileDropList(scNew);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            RemoveImageFilesFromClipboard(new string[] { ".gif", ".jpg", ".bmp", ".tiff" });
        }


sedgwick?
Can you correct your code now?  please , so we can close this post.


thank you
0
 
systanAuthor Commented:
C¿m on anh
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.