Solved

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

Posted on 2011-03-01
35
455 Views
Last Modified: 2013-12-17
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
0
Comment
Question by:systan
  • 23
  • 11
35 Comments
 
LVL 5

Assisted Solution

by:sindhuxyz
sindhuxyz earned 150 total points
ID: 35005862
0
 
LVL 14

Author Comment

by:systan
ID: 35006031
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
 
LVL 14

Author Comment

by:systan
ID: 35006129
sindhuxyz;
I think your links are not relevant for a solution
0
 
LVL 42

Accepted Solution

by:
sedgwick earned 350 total points
ID: 35006714
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
 
LVL 14

Author Comment

by:systan
ID: 35009214
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
 
LVL 42

Expert Comment

by:sedgwick
ID: 35009245
it only validates the extension of the file
0
 
LVL 14

Author Comment

by:systan
ID: 35009690
Ahm, does that validate before a file creation is made? or I guess after?
0
 
LVL 14

Author Comment

by:systan
ID: 35014662
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
 
LVL 14

Author Comment

by:systan
ID: 35015453
sedgwick?
0
 
LVL 42

Expert Comment

by:sedgwick
ID: 35015689
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
 
LVL 14

Author Comment

by:systan
ID: 35017671
>>to hook copying ?
you meant to hook pasting? or renaming it?


thanks
0
 
LVL 42

Expert Comment

by:sedgwick
ID: 35017696
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
 
LVL 14

Author Comment

by:systan
ID: 35017967
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
 
LVL 14

Author Comment

by:systan
ID: 35017975
>>all of them?
Ohm, but I hope BEFORE a file is created, not after.
0
 
LVL 14

Author Comment

by:systan
ID: 35018033
WatcherChangeTypes.Created is AFTER
WaitForChanged is BEFORE?
I'm really confused.
0
 
LVL 42

Expert Comment

by:sedgwick
ID: 35018116
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
 
LVL 42

Expert Comment

by:sedgwick
ID: 35018127
change the folder path (currently it's c:\temp) on line 14
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 14

Author Comment

by:systan
ID: 35018211
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
 
LVL 42

Expert Comment

by:sedgwick
ID: 35018256
10x alot man
0
 
LVL 14

Author Comment

by:systan
ID: 35018349
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
 
LVL 14

Author Comment

by:systan
ID: 35018366
>>man?
lol, Sorry, I'm over exited of what you did.
0
 
LVL 42

Expert Comment

by:sedgwick
ID: 35018398
Console.WriteLine or log to a file
0
 
LVL 14

Author Comment

by:systan
ID: 35018471
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
 
LVL 14

Author Comment

by:systan
ID: 35025790
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
 
LVL 42

Expert Comment

by:sedgwick
ID: 35026134
FileWatcher is for files, did u test the code?
0
 
LVL 14

Author Comment

by:systan
ID: 35026398
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
 
LVL 42

Expert Comment

by:sedgwick
ID: 35026417
that's true, thats why the code has the File.Delete function.
0
 
LVL 14

Author Comment

by:systan
ID: 35027242
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
 
LVL 14

Author Comment

by:systan
ID: 35027299
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
 
LVL 42

Expert Comment

by:sedgwick
ID: 35027536
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
 
LVL 14

Author Comment

by:systan
ID: 35028415
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
 
LVL 14

Author Comment

by:systan
ID: 35028440
Oh, StringCollection is not good with .NET 2.0
0
 
LVL 14

Author Comment

by:systan
ID: 35029759
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
 
LVL 14

Author Comment

by:systan
ID: 35033830
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
 
LVL 14

Author Closing Comment

by:systan
ID: 35037767
C¿m on anh
0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
Introduction Raise your hands if you were as upset with FireMonkey as I was when I discovered that there was no TListview.  I use TListView in almost all of my applications I've written, and I was not going to compromise by resorting to TStringGrid…
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now