コード例 #1
0
        public void StdFSDirGetFileNotNullTest()
        {
            root.CreateFile("root.txt");
            File422 file = root.GetFile("root.txt");

            Assert.NotNull(file);
        }
コード例 #2
0
        public void g_GetFileWrite()
        {
            //Dir422 dir = new StdFSDir(rootDir, true);
            //File422 fooFile = dir.GetFile("fooFile");
            //Stream fs = fooFile.OpenReadWrite();
            //string s = "Hello World";
            //fs.Write(Encoding.ASCII.GetBytes(s), 0, s.Length);
            File422 fooFile = root.GetFile("fooFile");
            Stream  fs      = fooFile.OpenReadWrite();
            string  s       = "Hello World";

            fs.Write(Encoding.ASCII.GetBytes(s), 0, s.Length);
        }
コード例 #3
0
        public void f_ReadFileMany()
        {
            File422 testFile = root.GetFile("testFile");
            Stream  fs       = testFile.OpenReadOnly();
            Stream  fs1      = testFile.OpenReadOnly();
            Stream  fs2      = testFile.OpenReadOnly();

            Assert.AreNotEqual(null, fs);
            Assert.AreNotEqual(null, fs1);
            Assert.AreNotEqual(null, fs2);
            fs.Dispose();
            fs1.Dispose();
            fs2.Dispose();
        }
コード例 #4
0
ファイル: tests.cs プロジェクト: Drew-Miller/CS422
        public void SDirTests()
        {
            StandardFileSystem sfs2 = StandardFileSystem.Create("/Users/drewm");

            Dir422 dir1 = sfs2.GetRoot().GetDir("Desktop");

            //Assert.NotNull(dir1.CreateFile("hello.txt"));
            //Assert.NotNull(dir1.CreateFile("Test.txt"));

            Assert.NotNull(dir1.CreateFile("A"));
            string datastring = "new data";

            byte[] info = new UTF8Encoding(true).GetBytes(datastring);

            File422 a = dir1.GetFile("A");

            if (a is StdFSFile)
            {
                Assert.NotNull(a);
                a = a as StdFSFile;

                FileStream fs = (FileStream)((StdFSFile)a).OpenReadWrite();
                fs.Write(info, 0, info.Length);
                fs.Close();
            }

            else
            {
                Assert.IsTrue(false);
            }
        }
コード例 #5
0
ファイル: Program.cs プロジェクト: Drew-Miller/CS422
        static int Main(string[] args)
        {
            StandardFileSystem sfs2 = StandardFileSystem.Create("/Users/drewm");

            Dir422 dir1 = sfs2.GetRoot().GetDir("Desktop");

            //Assert.NotNull(dir1.CreateFile("hello.txt"));
            //Assert.NotNull(dir1.CreateFile("Test.txt"));

            dir1.CreateFile("A");
            string datastring = "new data";

            byte[] info = new UTF8Encoding(true).GetBytes(datastring);

            File422 a = dir1.GetFile("A");

            if (a is StdFSFile)
            {
                a = a as StdFSFile;

                FileStream fs = (FileStream)((StdFSFile)a).OpenReadWrite();
                fs.Write(info, 0, info.Length);
                fs.Close();
            }

            return(0);
        }
コード例 #6
0
ファイル: FilesWebService.cs プロジェクト: jakeknott/CS422
        public override void Handler(WebRequest req)
        {
            if (!req.URI.StartsWith(this.ServiceURI))
            {
                throw new InvalidOperationException();
            }

            // Percent-decode our filename
            string percenDecoded = Uri.UnescapeDataString(req.URI);

            //If we want the root folder
            if (percenDecoded == ServiceURI)
            {
                RespondWithList(r_sys.GetRoot(), req);
                return;
            }

            // The pluse one is the '/' after the '/files' so we remove '/files/'
            string[] peices = percenDecoded.Substring(ServiceURI.Length + 1).Split('/');

            Dir422 dir = r_sys.GetRoot();

            for (int i = 0; i < peices.Length - 1; i++)
            {
                dir = dir.GetDir(peices[i]);

                if (dir == null)
                {
                    //This wants a response?
                    req.WriteNotFoundResponse(string.Empty);
                    return;
                }
            }

            string lastPeice = peices [peices.Length - 1];


            File422 file = dir.GetFile(lastPeice);

            if (file != null)
            {
                //Send back the file to them.
                RespondWithFile(file, req);
            }
            else
            {
                //Send the dir contents (if it is a dir to send back)
                dir = dir.GetDir(lastPeice);
                if (dir != null)
                {
                    //Respond with the list of files and dirs
                    RespondWithList(dir, req);
                }
                else
                {
                    req.WriteNotFoundResponse(string.Empty);
                }
            }
        }
コード例 #7
0
        private void GetHandler(WebRequest req)
        {
            //NOTE use Uri.UnescapeDataString to convert the escaped string
            //to it's unescaped representation.
            //i.e if we get http://localhost:4220/%20test/
            //would become http://localhost:4220/ test/
            string[] names = Uri.UnescapeDataString(req.RequestTarget).Split(new char[] { '/' },
                                                                             StringSplitOptions.RemoveEmptyEntries);

            //first name is files.
            string currString = "";

            Dir422  currNode = _fs.GetRoot(); //root is what we chose, the client knows it as "files".
            Dir422  nextNode = null;
            File422 file     = null;

            int uriCase = 1;

            for (int i = 1; i < names.Length; i++)
            {
                currString = names[i];
                if ((nextNode = currNode.GetDir(currString)) != null)
                {
                    //go to next dir to repeat iteration.
                    currNode = nextNode;
                }
                else if ((file = currNode.GetFile(currString)) != null)
                {
                    uriCase = 2;
                    break;
                }
                else
                {
                    uriCase = 3;
                    break;
                }
            }

            switch (uriCase)
            {
            //URI maps to an existing directory in the file system.
            case 1:
                string htmlString = BuildDirHTML(currNode);
                req.WriteHTMLResponse(htmlString);
                break;

            //The URI maps to an existing file in the file system
            case 2:
                SendFileContent(file, req);
                break;

            //The URI maps to something that doesn’t exist in the file system
            case 3:
                req.WriteNotFoundResponse(errorHtml);
                break;
            }
        }
コード例 #8
0
ファイル: tests.cs プロジェクト: Drew-Miller/CS422
        public void SSysContains()
        {
            StandardFileSystem sfs2 = StandardFileSystem.Create("/Users/drewm");

            Dir422 dir1 = sfs2.GetRoot().GetDir("Desktop");
            Dir422 dir2 = dir1.GetDir("Ableton");
            Dir422 dir3 = dir2.GetDir("wav files");

            File422 f = dir3.GetFile("Cloud.wav");

            Assert.IsTrue(sfs2.Contains(f));
        }
コード例 #9
0
ファイル: tests.cs プロジェクト: Drew-Miller/CS422
        public void SFileTests()
        {
            StandardFileSystem sfs2 = StandardFileSystem.Create("/Users/drewm");

            Dir422 dir1 = sfs2.GetRoot().GetDir("Desktop");
            Dir422 dir2 = dir1.GetDir("Ableton");
            Dir422 dir3 = dir2.GetDir("wav files");

            File422 f = dir3.GetFile("Cloud.wav");

            StringAssert.AreEqualIgnoringCase(f.Name, "Cloud.wav");
            StringAssert.AreEqualIgnoringCase(f.Parent.Name, "wav files");
        }
コード例 #10
0
ファイル: FilesWebService.cs プロジェクト: genewlee/CS422
        public override void Handler(WebRequest req)
        {
            if (!req.RequestURI.StartsWith(ServiceURI, StringComparison.CurrentCulture))
            {
                throw new InvalidOperationException();
            }

            if (req.RequestURI == "/files" || req.RequestURI == "/files/")
            {
                RespondWithList(m_fs.GetRoot(), req);
                return;
            }

            string[] pieces = req.RequestURI.Substring(ServiceURI.Length).Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
            if (pieces == null || pieces.Length == 0)
            {
                req.WriteNotFoundResponse("404: Path error.");
                return;
            }
            Dir422 dir = m_fs.GetRoot();

            for (int i = 0; i < pieces.Length - 1; i++)
            {
                string piece = pieces[i];
                dir = dir.GetDir(piece);
                if (dir == null)
                {
                    req.WriteNotFoundResponse("404: Path error.");
                    return;
                }
            }

            string name = PercentDecoding(pieces[pieces.Length - 1]);

            File422 file = dir.GetFile(name);

            if (file != null)
            {
                RespondWithFile(file, req);
                return;
            }

            dir = dir.GetDir(name);
            if (dir == null)
            {
                req.WriteNotFoundResponse("404: Path error.");
                return;
            }
            RespondWithList(dir, req);
        }
コード例 #11
0
ファイル: FilesWebService.cs プロジェクト: genewlee/CS422
        private void GETHandler(WebRequest req, string name, Dir422 dir)
        {
            File422 file = dir.GetFile(name);

            if (file != null)
            {
                RespondWithFile(file, req);
                return;
            }

            dir = dir.GetDir(name);
            if (dir == null)
            {
                req.WriteNotFoundResponse("404: Path error.");
                return;
            }
            RespondWithList(dir, req);
        }
コード例 #12
0
        public override void Handler(WebRequest req)
        {
            if (!req.URI.StartsWith(ServiceURI, StringComparison.Ordinal))
            {
                throw new InvalidOperationException();
            }

            //split the path
            string[] places = req.URI.Substring(ServiceURI.Length).Split('/');
            Dir422   dir    = r_sys.GetRoot();

            for (int i = 0; i < places.Length - 1; i++)
            {
                dir = dir.GetDir(places[i]);
                if (dir == null)
                {
                    req.WriteNotFoundResponse("");
                    return;
                }
            }

            File422 file = dir.GetFile(places[places.Length - 1]);

            if (file != null)
            {
                RespondWithFile(file, req);
            }

            else
            {
                dir = dir.GetDir(places[places.Length - 1]);
                if (dir != null)
                {
                    RespondWithList(dir, req);
                }

                else
                {
                    req.WriteNotFoundResponse("");
                }
            }
        }
コード例 #13
0
ファイル: tests.cs プロジェクト: Drew-Miller/CS422
        public void SgetDir_File()
        {
            StandardFileSystem sfs2 = StandardFileSystem.Create("/Users/drewm");
            Dir422             dir1 = sfs2.GetRoot().GetDir("Desktop");

            Assert.NotNull(dir1);


            Dir422 dir2 = dir1.GetDir("Ableton");

            Assert.NotNull(dir2);


            Dir422 dir3 = dir2.GetDir("wav files");

            Assert.NotNull(dir3);


            Assert.NotNull(dir3.GetFile("Cloud.wav"));
        }
コード例 #14
0
        public override void Handler(WebRequest req)
        {
            if (req.URI.Length < this.ServiceURI.Length)
            {
                req.URI = this.ServiceURI;
            }

            if (!req.URI.StartsWith(this.ServiceURI))
            {
                throw new InvalidOperationException();
            }



            uriPath = req.URI;

            string[] pieces = req.URI.Substring(ServiceURI.Length).Split('/'); //split up the path by '/' tokens

            if (pieces.Length == 1 && pieces[0] == "")                         //we passed in only the root
            {
                RespondWithList(r_sys.GetRoot(), req);
            }


            for (int x = 0; x < pieces.Length; x++)
            {
                pieces[x] = decode(pieces[x]);
            }


            Dir422 dir = r_sys.GetRoot(); //grab the root of the filesystem

            if (req.httpMethod == "PUT")  //if the method is put.
            {
                foreach (Tuple <string, string> header in req.headers)
                {
                    if (header.Item1 == "Content-Length")
                    {
                        if (Convert.ToInt64(header.Item2) <= 0)
                        {
                            req.WriteInvalidUpload("400");
                            return;
                        }
                    }
                }


                for (int i = 0; i < pieces.Length - 1; i++) //go through the parts of the path
                {
                    dir = dir.getDir(pieces[i]);
                    if (dir == null) //if you encounter a directory that doesn't exist, tell the user that the target they requested is not found and return
                    {
                        req.WriteNotFoundResponse("File not found.\n");
                        return;
                    }
                }



                File422 fileToCreate = dir.GetFile(pieces[pieces.Length - 1]); //grab the last file of the path
                if (fileToCreate == null)
                {
                    string pathName = StandardFileSystem.rootPath;

                    for (int i = 0; i < pieces.Length; i++)
                    {
                        pathName += "/";
                        pathName += pieces[i];
                    }

                    FileStream fs = new FileStream(pathName, FileMode.Create, FileAccess.ReadWrite);


                    int    x           = 0;
                    byte[] bodyBytes   = new byte[4096];
                    string bodyContent = "";

                    x = req.bodyStream.Read(bodyBytes, 0, 4096);
                    fs.Write(bodyBytes, 0, 4096);

                    while (x > 0)
                    {
                        bodyContent += Encoding.ASCII.GetString(bodyBytes);
                        x            = req.bodyStream.Read(bodyBytes, 0, 4096);
                        fs.Write(bodyBytes, 0, 4096);
                    }



                    fs.Close();

                    req.WriteHTMLResponse("200 OK");
                }

                else
                {
                    req.WriteInvalidUpload("File already exists");
                }


                return;
            }


            for (int i = 0; i < pieces.Length - 1; i++) //go through the parts of the path
            {
                dir = dir.getDir(pieces[i]);
                if (dir == null) //if you encounter a directory that doesn't exist, tell the user that the target they requested is not found and return
                {
                    req.WriteNotFoundResponse("File not found.\n");
                    return;
                }
            }

            //we now have the directory of one above the file / directory



            //one piece to process left
            //check if dir is in the last piece we have
            File422 file = dir.GetFile(pieces[pieces.Length - 1]); //grab the last file of the path

            if (file != null)
            {
                RespondWithFile(file, req);
            }
            else
            {
                dir = dir.getDir(pieces[pieces.Length - 1]); //if it wasn't a file, grab it as a dir
                if (dir != null)
                {
                    RespondWithList(dir, req);
                }
                else //if it's null, tell the user it was not found
                {
                    req.WriteNotFoundResponse("Not found\n");
                }
            }
        }
コード例 #15
0
        public override void Handler(WebRequest req)
        {
            //Every request should start with /files/
            if (!req.URI.StartsWith(this.ServiceURI))
            {
                throw new InvalidOperationException();
            }

            //percent-decode URI
            string uri = req.URI;

            string[] pieces = req.URI.Substring(ServiceURI.Length).Split('/', '\\');
            Dir422   dir    = _fs.GetRoot();
            //Grabs all the parts but the last part, which could be a file or a dir
            string piece = "";

            for (int i = 1; i < pieces.Length - 1; i++)
            {
                piece = pieces[i];
                //if (piece.Contains("%20")) piece = piece.Replace("%20", " ");
                dir = dir.GetDir(piece);

                //Check if directory exists
                if (dir == null)
                {
                    req.WriteNotFoundResponse();
                    return;
                }
            }


            //Check if the last part is a file or a directory
            piece = pieces[pieces.Length - 1];
            //if (piece.Contains("%20")) piece = piece.Replace("%20", " ");
            File422 file = dir.GetFile(piece); //TODO: This is returning Null and is not supposed to.

            if (file == null && req.Method == "PUT")
            {
                HandlePut(req, dir);
                return;
            }
            if (file != null)
            {
                //If it's a file, then return the file.
                Console.WriteLine("It's a file!");

                RespondWithFile(file, req);
            }
            else
            {
                piece = pieces[pieces.Length - 1];
                //if (piece.Contains("%20")) piece = piece.Replace("%20", " ");
                if (piece != "")
                {
                    dir = dir.GetDir(piece);
                }

                if (dir != null)
                {
                    //If it's a dir, return the dir
                    RespondWithList(dir, req);
                }
                else
                {
                    //Else return that nothing was found.
                    req.WriteNotFoundResponse();
                }
            }
        }
コード例 #16
0
        private void UploadFile(WebRequest req)
        {
            string[] pieces = req.URI.Substring(ServiceURI.Length).Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);

            if (pieces == null || pieces.Length == 0)
            {
                req.WriteNotFoundResponse("404: Path error.");
                return;
            }

            Dir422 dir = r_fs.GetRoot();

            for (int i = 0; i < pieces.Length - 1; i++)
            {
                string piece = pieces[i];
                dir = dir.GetDir(piece);

                if (dir == null)
                {
                    req.WriteNotFoundResponse("404: Path error.");
                    return;
                }
            }

            File422 file = dir.GetFile(PercentDecoding(pieces[pieces.Length - 1]));

            if (file != null)
            {
                req.WriteHTMLResponse("<html> File Already Exists! </html>");
                return;
            }

            File422    newFile = dir.CreateFile(PercentDecoding(pieces[pieces.Length - 1]));
            FileStream str     = (newFile.OpenReadWrite() as FileStream);
            Stream     reqStr  = req.Body;

            byte[] buf = new byte[4096];
            long   len = req.Len;

            if (len < 4096)
            {
                reqStr.Read(buf, 0, (int)len);
                str.Write(buf, 0, (int)len);
                str.Close();
                return;
            }

            int count     = reqStr.Read(buf, 0, 4096);
            int totalRead = count;

            while (count != 0 && totalRead < len)
            {
                str.Write(buf, 0, count);
                buf        = new byte[4096];
                count      = reqStr.Read(buf, 0, 4096);
                totalRead += count;
            }

            // If bytes were read last time, trim zeroes and write last bit
            if (count != 0)
            {
                str.Write(buf, 0, count);
            }

            str.Close();

            req.WriteHTMLResponse("<html> Upload Successful! </html>");

            return;
        }
コード例 #17
0
ファイル: NUnitTests.cs プロジェクト: jakeknott/CS422
        public void RunTest(FileSys422 mySys)
        {
            Dir422 root = mySys.GetRoot();

            //We should not be able to go above our root.
            Assert.IsNull(root.Parent);

            // Checking that we do not have a file
            Assert.IsFalse(root.ContainsFile("NewFile.txt", false));
            //create the file
            root.CreateFile("NewFile.txt");
            // Check that we can find it.
            Assert.IsTrue(root.ContainsFile("NewFile.txt", false));

            // Same with directory
            Assert.IsFalse(root.ContainsDir("SubDir", false));
            Dir422 subDir = root.CreateDir("SubDir");

            Assert.IsTrue(root.ContainsDir("SubDir", false));

            //Creating a file in a sub dir
            subDir.CreateFile("subText.txt");

            // Testing the recursive methods on files
            Assert.IsFalse(root.ContainsFile("subText.txt", false));
            Assert.IsTrue(root.ContainsFile("subText.txt", true));

            //Testing recurcive method on dirs
            subDir.CreateDir("newSubDir");

            Assert.IsFalse(root.ContainsDir("newSubDir", false));
            Assert.IsTrue(root.ContainsDir("newSubDir", true));

            //Checking getDir
            Dir422 recivedDir = root.GetDir("InvalidDir");

            Assert.IsNull(recivedDir);
            recivedDir = root.GetDir("SubDir");
            Assert.AreEqual("SubDir", recivedDir.Name);

            // Checking that if a file does not exist we return null,
            // otherwise we recived the file we wanted.
            File422 recidedFile = root.GetFile("InvalidFile");

            Assert.IsNull(recidedFile);
            recidedFile = root.GetFile("NewFile.txt");
            Assert.AreEqual("NewFile.txt", recidedFile.Name);

            //Checking the name validation function.
            // All of these methods use the same Validate Name method.
            Assert.IsNull(subDir.CreateFile("file/New.txt"));
            Assert.IsNull(subDir.CreateDir("file/New"));

            string bufString = "hello world";

            byte[] buff        = ASCIIEncoding.ASCII.GetBytes(bufString);
            var    writeStream = recidedFile.OpenReadWrite();

            writeStream.Write(buff, 0, 11);

            var readStream = recidedFile.OpenReadOnly();

            Assert.IsNull(readStream);

            writeStream.Dispose();

            readStream = recidedFile.OpenReadOnly();
            Assert.IsNotNull(readStream);

            //First read 'hello ' from each stream
            byte[] readBuf = new byte[6];
            readStream.Read(readBuf, 0, 6);
            Assert.AreEqual("hello ", ASCIIEncoding.ASCII.GetString(readBuf));

            //Having two streams open for read
            var readStream2 = recidedFile.OpenReadOnly();

            Assert.IsNotNull(readStream2);

            byte[] readBuf2 = new byte[6];
            readStream2.Read(readBuf2, 0, 6);
            Assert.AreEqual("hello ", ASCIIEncoding.ASCII.GetString(readBuf2));

            //Next read 'world' from each stream
            readBuf = new byte[5];
            readStream.Read(readBuf, 0, 5);
            Assert.AreEqual("world", ASCIIEncoding.ASCII.GetString(readBuf));

            readBuf2 = new byte[5];
            readStream2.Read(readBuf2, 0, 5);
            Assert.AreEqual("world", ASCIIEncoding.ASCII.GetString(readBuf2));

            //try to open a stream to write while there are streams open for read
            writeStream = recidedFile.OpenReadWrite();
            Assert.IsNull(writeStream);

            //Close streams and try again
            readStream.Close();
            readStream2.Close();

            writeStream = recidedFile.OpenReadWrite();
            Assert.IsNotNull(writeStream);
        }
コード例 #18
0
        void handleGET(WebRequest req)
        {
            try
            {
                string[] path = req.URI.Split('/');

                // To handle '/files' request
                if (path.Length == 2)
                {
                    req.WriteHTMLResponse(BuildDirHTML(fileSystem.GetRoot()));

                    return;
                }

                // This handles '/files/**'
                // The URI maps to an existing directory in the file system
                if (fileSystem.GetRoot().ContainsDir(path[path.Length - 1], true))
                {
                    // Imidiately set the content-type to html since we are returning html code
                    req.Headers["content-type"] = "text/html";

                    Dir422 currentDir = fileSystem.GetRoot();
                    for (int i = 2; i < path.Length; i++)
                    {
                        // Fix '/' at end of URI
                        if (path[i] != "")
                        {
                            currentDir = currentDir.GetDir(path[i]);
                        }
                    }

                    req.WriteHTMLResponse(BuildDirHTML(currentDir));
                }
                // The URI maps to an existing file in the file system
                else if (fileSystem.GetRoot().ContainsFile(path[path.Length - 1], true))
                {
                    // Get the file type and set the content-type to the file type
                    string filename = path[path.Length - 1];

                    int    dot  = filename.LastIndexOf('.');
                    string type = (dot >= 0) ? filename.Substring(dot).ToLower() : "";

                    switch (type)
                    {
                    case ".txt":
                        req.Headers["content-type"] = "text/plain";
                        break;

                    case ".xml":
                        req.Headers["content-type"] = "text/xml";
                        break;

                    case ".jpg":
                        req.Headers["content-type"] = "image/jpg";
                        break;

                    case ".jpeg":
                        req.Headers["content-type"] = "image/jpeg";
                        break;

                    case ".png":
                        req.Headers["content-type"] = "image/png";
                        break;

                    case ".mp4":
                        req.Headers["content-type"] = "video/mp4";
                        break;

                    case ".pdf":
                        req.Headers["content-type"] = "application/pdf";
                        break;

                    default:
                        req.Headers["content-type"] = "text/html";
                        break;
                    }

                    Dir422 currentDir = fileSystem.GetRoot();

                    // Don't include last element because thats the file name
                    for (int i = 2; i < path.Length - 1; i++)
                    {
                        // Fix '/' at end of URI
                        if (path[i] != "")
                        {
                            currentDir = currentDir.GetDir(path[i]);
                        }
                    }

                    File422 file = currentDir.GetFile(path[path.Length - 1]);

                    // Get the file stuff
                    int bytesRead;

                    // Did the client send us a range header
                    string rangeValue;
                    if (req.Headers.TryGetValue("range", out rangeValue))
                    {
                        byte[] buffer;

                        // Send the chunk they want. Only works for bytes=%d-%d
                        rangeValue = rangeValue.Replace(" ", "");
                        rangeValue = rangeValue.Remove(0, "bytes=".Length);
                        string[] bytes = rangeValue.Split('-');
                        int      start = int.Parse(bytes[0]), end = int.Parse(bytes[1]), totalRead = 0;
                        buffer = new byte[end - start];

                        using (BufferedStream reader = new BufferedStream(file.OpenReadOnly()))
                        {
                            // Add header = content-range: bytes %d-%d/%d
                            req.Headers["content-range"] = "bytes " + rangeValue + "/" + reader.Length;

                            req.WritePreBody(206, buffer.Length);

                            while ((bytesRead = reader.Read(buffer, 0, buffer.Length)) > 0)
                            {
                                req.WriteFile(buffer, totalRead, bytesRead);

                                totalRead += bytesRead;
                            }
                        }
                    }
                    else
                    {
                        // Send the entire thing
                        BufferedStream reader = new BufferedStream(file.OpenReadOnly());
                        byte[]         buffer = new byte[8 * 1024];

                        req.WritePreBody(200, reader.Length);

                        while ((bytesRead = reader.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            req.WriteFile(buffer, 0, bytesRead);
                        }

                        reader.Close();
                    }
                }
                else
                {
                    // The URI maps to something that doesn’t exist in the file system
                    req.WriteNotFoundResponse("<h1>404</h1><br><b>Content not found</b>");
                }
            }
            catch (Exception)
            {
                return;
            }
        }
コード例 #19
0
        public override void Handler(WebRequest Req)
        {
            Dir422 Root = m_FS.GetRoot();

            //Remove Last / here!!!!
            if (Req.URI.LastIndexOf('/') == Req.URI.Length - 1)
            {
                Req.URI = Req.URI.Substring(0, Req.URI.Length - 1);
            }
            //int x = 0;


            //1. Percent-decode URI.
            // THIS NOT GOOD ENOUGH!!!

            Req.URI = Utility.PercentDecode(Req.URI);
            //string test = Req.URI.Replace ("%20", " ");;

            // Set name of requested file||dir.
            string uriName = Utility.NameFromPath(Req.URI);

            //2. If it refers to file somewhere in the shared folder.
            if (Root.ContainsFile(uriName, true))
            {
                string path = Req.URI.Substring(0, Req.URI.LastIndexOf("/"));

                Dir422     Dir          = Utility.TraverseToDir(Root, path);
                StdFSFile  File         = (StdFSFile)Dir.GetFile(uriName);
                FileStream MyFileStream = (FileStream)File.OpenReadOnly();

                if (Req.headers.ContainsKey("Range"))
                {
                    // process partial response here
                    Console.WriteLine("Process Partial Request");
                    int x = 0;
                }
                else
                {
                    string contentType = Utility.ContentType(uriName);
                    string response    = Utility.BuildFileResponseString(
                        MyFileStream.Length.ToString(), contentType);

                    //if (contentType != "video/mp4")
                    //{
                    byte[] sendResponseString = Encoding.ASCII.GetBytes(response);
                    Req.bodyRequest.Write(sendResponseString, 0, sendResponseString.Length);
                    //}

                    //byte[] sendResponseString = Encoding.ASCII.GetBytes(response);

                    int    read = 0;
                    byte[] send = new byte[7500];

                    while (read < MyFileStream.Length)
                    {
                        read = read + MyFileStream.Read(send, 0, send.Length);
                        Req.bodyRequest.Write(send, 0, send.Length);
                    }
                }
            }

            //3. Else if it refers to a folder somewhere in the shared folder.
            //	 Or is the shared directory
            else if (Root.ContainsDir(uriName, true) || Req.URI == ServiceURI || uriName == "")
            {
                if (Req.URI == ServiceURI || uriName == "")
                {
                    string dirHTMLListing = BuildDirHTML(Root);

                    byte[] sendResponseString = Encoding.ASCII.GetBytes(dirHTMLListing);
                    Req.bodyRequest.Write(sendResponseString, 0, sendResponseString.Length);

                    //Req.WriteHTMLResponse (dirHTMLListing);
                }
                else
                {
                    Dir422 Dir            = Utility.TraverseToDir(Root, Req.URI);
                    string dirHTMLListing = BuildDirHTML(Dir);

                    byte[] sendResponseString = Encoding.ASCII.GetBytes(dirHTMLListing);
                    Req.bodyRequest.Write(sendResponseString, 0, sendResponseString.Length);

                    //Req.WriteHTMLResponse (dirHTMLListing);
                }
            }

            //4.Else it’s a bad URI.
            else
            {
                Req.WriteNotFoundResponse("File or directory not found");
            }
        }