SftpTests.cs 225 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349
  1. using System.Diagnostics;
  2. using Renci.SshNet.Common;
  3. using Renci.SshNet.IntegrationTests.Common;
  4. using Renci.SshNet.Sftp;
  5. namespace Renci.SshNet.IntegrationTests
  6. {
  7. // TODO: DeleteDirectory (fail + success
  8. // TODO: DeleteFile (fail + success
  9. // TODO: Delete (fail + success
  10. [TestClass]
  11. public class SftpTests : TestBase
  12. {
  13. private IConnectionInfoFactory _connectionInfoFactory;
  14. private IConnectionInfoFactory _adminConnectionInfoFactory;
  15. private IRemotePathTransformation _remotePathTransformation;
  16. [TestInitialize]
  17. public void SetUp()
  18. {
  19. _connectionInfoFactory = new LinuxVMConnectionFactory(SshServerHostName, SshServerPort);
  20. _adminConnectionInfoFactory = new LinuxAdminConnectionFactory(SshServerHostName, SshServerPort);
  21. _remotePathTransformation = RemotePathTransformation.ShellQuote;
  22. }
  23. #if FEATURE_MSTEST_DATATEST
  24. [DataTestMethod]
  25. [DynamicData(nameof(GetSftpUploadFileFileStreamData), DynamicDataSourceType.Method)]
  26. #else
  27. [TestMethod]
  28. public void Sftp_Upload_DirectoryInfo_ExistingFile()
  29. {
  30. foreach (var data in GetSftpUploadFileFileStreamData())
  31. {
  32. Sftp_UploadFile_FileStream((int) data[0]);
  33. }
  34. }
  35. #endif
  36. public void Sftp_UploadFile_FileStream(int size)
  37. {
  38. var file = CreateTempFile(size);
  39. using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read))
  40. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  41. {
  42. client.Connect();
  43. var remoteFile = GenerateUniqueRemoteFileName();
  44. if (client.Exists(remoteFile))
  45. {
  46. client.Delete(remoteFile);
  47. }
  48. try
  49. {
  50. client.UploadFile(fs, remoteFile);
  51. using (var memoryStream = new MemoryStream(size))
  52. {
  53. client.DownloadFile(remoteFile, memoryStream);
  54. memoryStream.Position = 0;
  55. Assert.AreEqual(CreateFileHash(file), CreateHash(memoryStream));
  56. }
  57. }
  58. finally
  59. {
  60. if (client.Exists(remoteFile))
  61. {
  62. client.Delete(remoteFile);
  63. }
  64. }
  65. }
  66. }
  67. [TestMethod]
  68. public void Sftp_ConnectDisconnect_Serial()
  69. {
  70. const int iterations = 100;
  71. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  72. {
  73. for (var i = 1; i <= iterations; i++)
  74. {
  75. client.Connect();
  76. client.Disconnect();
  77. }
  78. }
  79. }
  80. [TestMethod]
  81. public void Sftp_ConnectDisconnect_Parallel()
  82. {
  83. const int iterations = 10;
  84. const int threads = 20;
  85. var startEvent = new ManualResetEvent(false);
  86. var tasks = Enumerable.Range(1, threads).Select(i =>
  87. {
  88. return Task.Factory.StartNew(() =>
  89. {
  90. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  91. {
  92. startEvent.WaitOne();
  93. for (var j = 0; j < iterations; j++)
  94. {
  95. client.Connect();
  96. client.Disconnect();
  97. }
  98. }
  99. });
  100. }).ToArray();
  101. startEvent.Set();
  102. Task.WaitAll(tasks);
  103. }
  104. [TestMethod]
  105. public void Sftp_BeginUploadFile()
  106. {
  107. const string content = "SftpBeginUploadFile";
  108. var expectedByteCount = (ulong) Encoding.ASCII.GetByteCount(content);
  109. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  110. {
  111. client.Connect();
  112. var remoteFile = GenerateUniqueRemoteFileName();
  113. if (client.Exists(remoteFile))
  114. {
  115. client.Delete(remoteFile);
  116. }
  117. try
  118. {
  119. using (var memoryStream = new MemoryStream(Encoding.ASCII.GetBytes(content)))
  120. {
  121. IAsyncResult asyncResultCallback = null;
  122. var asyncResult = client.BeginUploadFile(memoryStream, remoteFile, ar => asyncResultCallback = ar);
  123. Assert.IsTrue(asyncResult.AsyncWaitHandle.WaitOne(10000));
  124. // check async result
  125. var sftpUploadAsyncResult = asyncResult as SftpUploadAsyncResult;
  126. Assert.IsNotNull(sftpUploadAsyncResult);
  127. Assert.IsFalse(sftpUploadAsyncResult.IsUploadCanceled);
  128. Assert.IsTrue(sftpUploadAsyncResult.IsCompleted);
  129. Assert.IsFalse(sftpUploadAsyncResult.CompletedSynchronously);
  130. Assert.AreEqual(expectedByteCount, sftpUploadAsyncResult.UploadedBytes);
  131. // check async result callback
  132. var sftpUploadAsyncResultCallback = asyncResultCallback as SftpUploadAsyncResult;
  133. Assert.IsNotNull(sftpUploadAsyncResultCallback);
  134. Assert.IsFalse(sftpUploadAsyncResultCallback.IsUploadCanceled);
  135. Assert.IsTrue(sftpUploadAsyncResultCallback.IsCompleted);
  136. Assert.IsFalse(sftpUploadAsyncResultCallback.CompletedSynchronously);
  137. Assert.AreEqual(expectedByteCount, sftpUploadAsyncResultCallback.UploadedBytes);
  138. }
  139. // check uploaded file
  140. using (var memoryStream = new MemoryStream())
  141. {
  142. client.DownloadFile(remoteFile, memoryStream);
  143. memoryStream.Position = 0;
  144. var remoteContent = Encoding.ASCII.GetString(memoryStream.ToArray());
  145. Assert.AreEqual(content, remoteContent);
  146. }
  147. }
  148. finally
  149. {
  150. if (client.Exists(remoteFile))
  151. {
  152. client.Delete(remoteFile);
  153. }
  154. }
  155. }
  156. }
  157. [TestMethod]
  158. public void Sftp_Create_ExistingFile()
  159. {
  160. var encoding = Encoding.UTF8;
  161. var initialContent = "Gert & Ann & Lisa";
  162. var newContent1 = "Sofie";
  163. var newContent1Bytes = GetBytesWithPreamble(newContent1, encoding);
  164. var newContent2 = "Lisa & Sofie";
  165. var newContent2Bytes = GetBytesWithPreamble(newContent2, encoding);
  166. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  167. {
  168. client.Connect();
  169. var remoteFile = GenerateUniqueRemoteFileName();
  170. if (client.Exists(remoteFile))
  171. {
  172. client.DeleteFile(remoteFile);
  173. }
  174. try
  175. {
  176. client.WriteAllText(remoteFile, initialContent);
  177. #region Write less bytes than the current content, overwriting part of that content
  178. using (var fs = client.Create(remoteFile))
  179. using (var sw = new StreamWriter(fs, encoding))
  180. {
  181. sw.Write(newContent1);
  182. }
  183. var actualContent1 = client.ReadAllBytes(remoteFile);
  184. Assert.IsTrue(newContent1Bytes.IsEqualTo(actualContent1));
  185. #endregion Write less bytes than the current content, overwriting part of that content
  186. #region Write more bytes than the current content, overwriting and appending to that content
  187. using (var fs = client.Create(remoteFile))
  188. using (var sw = new StreamWriter(fs, encoding))
  189. {
  190. sw.Write(newContent2);
  191. }
  192. var actualContent2 = client.ReadAllBytes(remoteFile);
  193. Assert.IsTrue(newContent2Bytes.IsEqualTo(actualContent2));
  194. #endregion Write more bytes than the current content, overwriting and appending to that content
  195. }
  196. finally
  197. {
  198. if (client.Exists(remoteFile))
  199. {
  200. client.DeleteFile(remoteFile);
  201. }
  202. }
  203. }
  204. }
  205. [TestMethod]
  206. public void Sftp_Create_DirectoryDoesNotExist()
  207. {
  208. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  209. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  210. {
  211. client.Connect();
  212. if (client.Exists(remoteFile))
  213. {
  214. client.DeleteFile(remoteFile);
  215. }
  216. SftpFileStream fs = null;
  217. try
  218. {
  219. fs = client.Create(remoteFile);
  220. Assert.Fail();
  221. }
  222. catch (SftpPathNotFoundException ex)
  223. {
  224. Assert.IsNull(ex.InnerException);
  225. Assert.AreEqual("No such file", ex.Message);
  226. }
  227. finally
  228. {
  229. fs?.Dispose();
  230. if (client.Exists(remoteFile))
  231. {
  232. client.DeleteFile(remoteFile);
  233. }
  234. }
  235. }
  236. }
  237. [TestMethod]
  238. public void Sftp_Create_FileDoesNotExist()
  239. {
  240. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  241. {
  242. client.BufferSize = 512 * 1024;
  243. client.Connect();
  244. var remoteFile = GenerateUniqueRemoteFileName();
  245. if (client.Exists(remoteFile))
  246. {
  247. client.DeleteFile(remoteFile);
  248. }
  249. try
  250. {
  251. using (var imageStream = GetData("resources.issue #70.png"))
  252. {
  253. using (var fs = client.Create(remoteFile))
  254. {
  255. byte[] buffer = new byte[Math.Min(client.BufferSize, imageStream.Length)];
  256. int bytesRead;
  257. while ((bytesRead = imageStream.Read(buffer, offset: 0, buffer.Length)) > 0)
  258. {
  259. fs.Write(buffer, offset: 0, bytesRead);
  260. }
  261. }
  262. using (var memoryStream = new MemoryStream())
  263. {
  264. client.DownloadFile(remoteFile, memoryStream);
  265. memoryStream.Position = 0;
  266. imageStream.Position = 0;
  267. Assert.AreEqual(CreateHash(imageStream), CreateHash(memoryStream));
  268. }
  269. }
  270. }
  271. finally
  272. {
  273. if (client.Exists(remoteFile))
  274. {
  275. client.DeleteFile(remoteFile);
  276. }
  277. }
  278. }
  279. }
  280. [TestMethod]
  281. public void Sftp_AppendAllLines_NoEncoding_ExistingFile()
  282. {
  283. var initialContent = "\u0100ert & Ann";
  284. IEnumerable<string> linesToAppend = new[] { "Forever", "&", "\u0116ver" };
  285. var expectedContent = initialContent + string.Join(Environment.NewLine, linesToAppend) +
  286. Environment.NewLine;
  287. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  288. {
  289. client.Connect();
  290. var remoteFile = GenerateUniqueRemoteFileName();
  291. if (client.Exists(remoteFile))
  292. {
  293. client.DeleteFile(remoteFile);
  294. }
  295. try
  296. {
  297. client.WriteAllText(remoteFile, initialContent);
  298. client.AppendAllLines(remoteFile, linesToAppend);
  299. var text = client.ReadAllText(remoteFile);
  300. Assert.AreEqual(expectedContent, text);
  301. // ensure we didn't write an UTF-8 BOM
  302. using (var fs = client.OpenRead(remoteFile))
  303. {
  304. var firstByte = fs.ReadByte();
  305. Assert.AreEqual(Encoding.UTF8.GetBytes(expectedContent)[0], firstByte);
  306. }
  307. }
  308. finally
  309. {
  310. if (client.Exists(remoteFile))
  311. {
  312. client.DeleteFile(remoteFile);
  313. }
  314. }
  315. }
  316. }
  317. [TestMethod]
  318. public void Sftp_AppendAllLines_NoEncoding_DirectoryDoesNotExist()
  319. {
  320. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  321. IEnumerable<string> linesToAppend = new[] { "\u0139isa", "&", "Sofie" };
  322. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  323. {
  324. client.Connect();
  325. if (client.Exists(remoteFile))
  326. {
  327. client.DeleteFile(remoteFile);
  328. }
  329. try
  330. {
  331. client.AppendAllLines(remoteFile, linesToAppend);
  332. Assert.Fail();
  333. }
  334. catch (SftpPathNotFoundException ex)
  335. {
  336. Assert.IsNull(ex.InnerException);
  337. Assert.AreEqual("No such file", ex.Message);
  338. }
  339. finally
  340. {
  341. if (client.Exists(remoteFile))
  342. {
  343. client.DeleteFile(remoteFile);
  344. }
  345. }
  346. }
  347. }
  348. [TestMethod]
  349. public void Sftp_AppendAllLines_NoEncoding_FileDoesNotExist()
  350. {
  351. IEnumerable<string> linesToAppend = new[] { "\u0139isa", "&", "Sofie" };
  352. var expectedContent = string.Join(Environment.NewLine, linesToAppend) + Environment.NewLine;
  353. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  354. {
  355. client.Connect();
  356. var remoteFile = GenerateUniqueRemoteFileName();
  357. if (client.Exists(remoteFile))
  358. {
  359. client.DeleteFile(remoteFile);
  360. }
  361. try
  362. {
  363. client.AppendAllLines(remoteFile, linesToAppend);
  364. var text = client.ReadAllText(remoteFile);
  365. Assert.AreEqual(expectedContent, text);
  366. // ensure we didn't write an UTF-8 BOM
  367. using (var fs = client.OpenRead(remoteFile))
  368. {
  369. var firstByte = fs.ReadByte();
  370. Assert.AreEqual(Encoding.UTF8.GetBytes(expectedContent)[0], firstByte);
  371. }
  372. }
  373. finally
  374. {
  375. if (client.Exists(remoteFile))
  376. {
  377. client.DeleteFile(remoteFile);
  378. }
  379. }
  380. }
  381. }
  382. [TestMethod]
  383. public void Sftp_AppendAllText_NoEncoding_ExistingFile()
  384. {
  385. var initialContent = "\u0100ert & Ann";
  386. var contentToAppend = "Forever&\u0116ver";
  387. var expectedContent = initialContent + contentToAppend;
  388. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  389. {
  390. client.Connect();
  391. var remoteFile = GenerateUniqueRemoteFileName();
  392. if (client.Exists(remoteFile))
  393. {
  394. client.DeleteFile(remoteFile);
  395. }
  396. try
  397. {
  398. client.WriteAllText(remoteFile, initialContent);
  399. client.AppendAllText(remoteFile, contentToAppend);
  400. var text = client.ReadAllText(remoteFile);
  401. Assert.AreEqual(expectedContent, text);
  402. // ensure we didn't write an UTF-8 BOM
  403. using (var fs = client.OpenRead(remoteFile))
  404. {
  405. var firstByte = fs.ReadByte();
  406. Assert.AreEqual(Encoding.UTF8.GetBytes(expectedContent)[0], firstByte);
  407. }
  408. }
  409. finally
  410. {
  411. if (client.Exists(remoteFile))
  412. {
  413. client.DeleteFile(remoteFile);
  414. }
  415. }
  416. }
  417. }
  418. [TestMethod]
  419. public void Sftp_AppendAllText_NoEncoding_DirectoryDoesNotExist()
  420. {
  421. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  422. var contentToAppend = "Forever&\u0116ver";
  423. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  424. {
  425. client.Connect();
  426. if (client.Exists(remoteFile))
  427. {
  428. client.DeleteFile(remoteFile);
  429. }
  430. try
  431. {
  432. client.AppendAllText(remoteFile, contentToAppend);
  433. Assert.Fail();
  434. }
  435. catch (SftpPathNotFoundException ex)
  436. {
  437. Assert.IsNull(ex.InnerException);
  438. Assert.AreEqual("No such file", ex.Message);
  439. }
  440. finally
  441. {
  442. if (client.Exists(remoteFile))
  443. {
  444. client.DeleteFile(remoteFile);
  445. }
  446. }
  447. }
  448. }
  449. [TestMethod]
  450. public void Sftp_AppendAllText_NoEncoding_FileDoesNotExist()
  451. {
  452. var contentToAppend = "Forever&\u0116ver";
  453. var expectedContent = contentToAppend;
  454. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  455. {
  456. client.Connect();
  457. var remoteFile = GenerateUniqueRemoteFileName();
  458. if (client.Exists(remoteFile))
  459. {
  460. client.DeleteFile(remoteFile);
  461. }
  462. try
  463. {
  464. client.AppendAllText(remoteFile, contentToAppend);
  465. var text = client.ReadAllText(remoteFile);
  466. Assert.AreEqual(expectedContent, text);
  467. // ensure we didn't write an UTF-8 BOM
  468. using (var fs = client.OpenRead(remoteFile))
  469. {
  470. var firstByte = fs.ReadByte();
  471. Assert.AreEqual(Encoding.UTF8.GetBytes(expectedContent)[0], firstByte);
  472. }
  473. }
  474. finally
  475. {
  476. if (client.Exists(remoteFile))
  477. {
  478. client.DeleteFile(remoteFile);
  479. }
  480. }
  481. }
  482. }
  483. [TestMethod]
  484. public void Sftp_AppendText_NoEncoding_ExistingFile()
  485. {
  486. var initialContent = "\u0100ert & Ann";
  487. var contentToAppend = "Forever&\u0116ver";
  488. var expectedContent = initialContent + contentToAppend;
  489. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  490. {
  491. client.Connect();
  492. var remoteFile = GenerateUniqueRemoteFileName();
  493. if (client.Exists(remoteFile))
  494. {
  495. client.DeleteFile(remoteFile);
  496. }
  497. try
  498. {
  499. client.WriteAllText(remoteFile, initialContent);
  500. using (var sw = client.AppendText(remoteFile))
  501. {
  502. sw.Write(contentToAppend);
  503. }
  504. var text = client.ReadAllText(remoteFile);
  505. Assert.AreEqual(expectedContent, text);
  506. // ensure we didn't write an UTF-8 BOM
  507. using (var fs = client.OpenRead(remoteFile))
  508. {
  509. var firstByte = fs.ReadByte();
  510. Assert.AreEqual(Encoding.UTF8.GetBytes(expectedContent)[0], firstByte);
  511. }
  512. }
  513. finally
  514. {
  515. if (client.Exists(remoteFile))
  516. {
  517. client.DeleteFile(remoteFile);
  518. }
  519. }
  520. }
  521. }
  522. [TestMethod]
  523. public void Sftp_AppendText_NoEncoding_DirectoryDoesNotExist()
  524. {
  525. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  526. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  527. {
  528. client.Connect();
  529. if (client.Exists(remoteFile))
  530. {
  531. client.DeleteFile(remoteFile);
  532. }
  533. StreamWriter sw = null;
  534. try
  535. {
  536. sw = client.AppendText(remoteFile);
  537. Assert.Fail();
  538. }
  539. catch (SftpPathNotFoundException ex)
  540. {
  541. Assert.IsNull(ex.InnerException);
  542. Assert.AreEqual("No such file", ex.Message);
  543. }
  544. finally
  545. {
  546. sw?.Dispose();
  547. if (client.Exists(remoteFile))
  548. {
  549. client.DeleteFile(remoteFile);
  550. }
  551. }
  552. }
  553. }
  554. [TestMethod]
  555. public void Sftp_AppendText_NoEncoding_FileDoesNotExist()
  556. {
  557. var contentToAppend = "\u0100ert & Ann";
  558. var expectedContent = contentToAppend;
  559. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  560. {
  561. client.Connect();
  562. var remoteFile = GenerateUniqueRemoteFileName();
  563. if (client.Exists(remoteFile))
  564. {
  565. client.DeleteFile(remoteFile);
  566. }
  567. try
  568. {
  569. using (var sw = client.AppendText(remoteFile))
  570. {
  571. sw.Write(contentToAppend);
  572. }
  573. // ensure we didn't write an UTF-8 BOM
  574. using (var fs = client.OpenRead(remoteFile))
  575. {
  576. var firstByte = fs.ReadByte();
  577. Assert.AreEqual(Encoding.UTF8.GetBytes(expectedContent)[0], firstByte);
  578. }
  579. }
  580. finally
  581. {
  582. if (client.Exists(remoteFile))
  583. {
  584. client.DeleteFile(remoteFile);
  585. }
  586. }
  587. }
  588. }
  589. [TestMethod]
  590. public void Sftp_AppendAllLines_Encoding_ExistingFile()
  591. {
  592. var initialContent = "\u0100ert & Ann";
  593. IEnumerable<string> linesToAppend = new[] { "Forever", "&", "\u0116ver" };
  594. var expectedContent = initialContent + string.Join(Environment.NewLine, linesToAppend) +
  595. Environment.NewLine;
  596. var encoding = GetRandomEncoding();
  597. var expectedBytes = GetBytesWithPreamble(expectedContent, encoding);
  598. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  599. {
  600. client.Connect();
  601. var remoteFile = GenerateUniqueRemoteFileName();
  602. if (client.Exists(remoteFile))
  603. {
  604. client.DeleteFile(remoteFile);
  605. }
  606. try
  607. {
  608. client.WriteAllText(remoteFile, initialContent, encoding);
  609. client.AppendAllLines(remoteFile, linesToAppend, encoding);
  610. var text = client.ReadAllText(remoteFile, encoding);
  611. Assert.AreEqual(expectedContent, text);
  612. using (var fs = client.OpenRead(remoteFile))
  613. {
  614. var actualBytes = new byte[fs.Length];
  615. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  616. Assert.IsTrue(expectedBytes.IsEqualTo(actualBytes));
  617. }
  618. }
  619. finally
  620. {
  621. if (client.Exists(remoteFile))
  622. {
  623. client.DeleteFile(remoteFile);
  624. }
  625. }
  626. }
  627. }
  628. [TestMethod]
  629. public void Sftp_AppendAllLines_Encoding_DirectoryDoesNotExist()
  630. {
  631. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  632. IEnumerable<string> linesToAppend = new[] { "Forever", "&", "\u0116ver" };
  633. var encoding = GetRandomEncoding();
  634. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  635. {
  636. client.Connect();
  637. if (client.Exists(remoteFile))
  638. {
  639. client.DeleteFile(remoteFile);
  640. }
  641. try
  642. {
  643. client.AppendAllLines(remoteFile, linesToAppend, encoding);
  644. Assert.Fail();
  645. }
  646. catch (SftpPathNotFoundException ex)
  647. {
  648. Assert.IsNull(ex.InnerException);
  649. Assert.AreEqual("No such file", ex.Message);
  650. }
  651. finally
  652. {
  653. if (client.Exists(remoteFile))
  654. {
  655. client.DeleteFile(remoteFile);
  656. }
  657. }
  658. }
  659. }
  660. [TestMethod]
  661. public void Sftp_AppendAllLines_Encoding_FileDoesNotExist()
  662. {
  663. IEnumerable<string> linesToAppend = new[] { "\u0139isa", "&", "Sofie" };
  664. var expectedContent = string.Join(Environment.NewLine, linesToAppend) + Environment.NewLine;
  665. var encoding = GetRandomEncoding();
  666. var expectedBytes = GetBytesWithPreamble(expectedContent, encoding);
  667. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  668. {
  669. client.Connect();
  670. var remoteFile = GenerateUniqueRemoteFileName();
  671. if (client.Exists(remoteFile))
  672. {
  673. client.DeleteFile(remoteFile);
  674. }
  675. try
  676. {
  677. client.AppendAllLines(remoteFile, linesToAppend, encoding);
  678. var text = client.ReadAllText(remoteFile, encoding);
  679. Assert.AreEqual(expectedContent, text);
  680. using (var fs = client.OpenRead(remoteFile))
  681. {
  682. var actualBytes = new byte[fs.Length];
  683. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  684. Assert.IsTrue(expectedBytes.IsEqualTo(actualBytes));
  685. }
  686. }
  687. finally
  688. {
  689. if (client.Exists(remoteFile))
  690. {
  691. client.DeleteFile(remoteFile);
  692. }
  693. }
  694. }
  695. }
  696. [TestMethod]
  697. public void Sftp_AppendAllText_Encoding_ExistingFile()
  698. {
  699. var initialContent = "\u0100ert & Ann";
  700. var contentToAppend = "Forever&\u0116ver";
  701. var expectedContent = initialContent + contentToAppend;
  702. var encoding = GetRandomEncoding();
  703. var expectedBytes = GetBytesWithPreamble(expectedContent, encoding);
  704. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  705. {
  706. client.Connect();
  707. var remoteFile = GenerateUniqueRemoteFileName();
  708. if (client.Exists(remoteFile))
  709. {
  710. client.DeleteFile(remoteFile);
  711. }
  712. try
  713. {
  714. client.WriteAllText(remoteFile, initialContent, encoding);
  715. client.AppendAllText(remoteFile, contentToAppend, encoding);
  716. var text = client.ReadAllText(remoteFile, encoding);
  717. Assert.AreEqual(expectedContent, text);
  718. using (var fs = client.OpenRead(remoteFile))
  719. {
  720. var actualBytes = new byte[fs.Length];
  721. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  722. Assert.IsTrue(expectedBytes.IsEqualTo(actualBytes));
  723. }
  724. }
  725. finally
  726. {
  727. if (client.Exists(remoteFile))
  728. {
  729. client.DeleteFile(remoteFile);
  730. }
  731. }
  732. }
  733. }
  734. [TestMethod]
  735. public void Sftp_AppendAllText_Encoding_DirectoryDoesNotExist()
  736. {
  737. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  738. const string contentToAppend = "Forever&\u0116ver";
  739. var encoding = GetRandomEncoding();
  740. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  741. {
  742. client.Connect();
  743. if (client.Exists(remoteFile))
  744. {
  745. client.DeleteFile(remoteFile);
  746. }
  747. try
  748. {
  749. client.AppendAllText(remoteFile, contentToAppend, encoding);
  750. Assert.Fail();
  751. }
  752. catch (SftpPathNotFoundException ex)
  753. {
  754. Assert.IsNull(ex.InnerException);
  755. Assert.AreEqual("No such file", ex.Message);
  756. }
  757. finally
  758. {
  759. if (client.Exists(remoteFile))
  760. {
  761. client.DeleteFile(remoteFile);
  762. }
  763. }
  764. }
  765. }
  766. [TestMethod]
  767. public void Sftp_AppendAllText_Encoding_FileDoesNotExist()
  768. {
  769. const string contentToAppend = "Forever&\u0116ver";
  770. var expectedContent = contentToAppend;
  771. var encoding = GetRandomEncoding();
  772. var expectedBytes = GetBytesWithPreamble(expectedContent, encoding);
  773. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  774. {
  775. client.Connect();
  776. var remoteFile = GenerateUniqueRemoteFileName();
  777. if (client.Exists(remoteFile))
  778. {
  779. client.DeleteFile(remoteFile);
  780. }
  781. try
  782. {
  783. client.AppendAllText(remoteFile, contentToAppend, encoding);
  784. var text = client.ReadAllText(remoteFile, encoding);
  785. Assert.AreEqual(expectedContent, text);
  786. using (var fs = client.OpenRead(remoteFile))
  787. {
  788. var actualBytes = new byte[fs.Length];
  789. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  790. Assert.IsTrue(expectedBytes.IsEqualTo(actualBytes));
  791. }
  792. }
  793. finally
  794. {
  795. if (client.Exists(remoteFile))
  796. {
  797. client.DeleteFile(remoteFile);
  798. }
  799. }
  800. }
  801. }
  802. [TestMethod]
  803. public void Sftp_AppendText_Encoding_ExistingFile()
  804. {
  805. const string initialContent = "\u0100ert & Ann";
  806. const string contentToAppend = "Forever&\u0116ver";
  807. var expectedContent = initialContent + contentToAppend;
  808. var encoding = GetRandomEncoding();
  809. var expectedBytes = GetBytesWithPreamble(expectedContent, encoding);
  810. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  811. {
  812. client.Connect();
  813. var remoteFile = GenerateUniqueRemoteFileName();
  814. if (client.Exists(remoteFile))
  815. {
  816. client.DeleteFile(remoteFile);
  817. }
  818. try
  819. {
  820. client.WriteAllText(remoteFile, initialContent, encoding);
  821. using (var sw = client.AppendText(remoteFile, encoding))
  822. {
  823. sw.Write(contentToAppend);
  824. }
  825. var text = client.ReadAllText(remoteFile, encoding);
  826. Assert.AreEqual(expectedContent, text);
  827. using (var fs = client.OpenRead(remoteFile))
  828. {
  829. var actualBytes = new byte[fs.Length];
  830. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  831. Assert.IsTrue(expectedBytes.IsEqualTo(actualBytes));
  832. }
  833. }
  834. finally
  835. {
  836. if (client.Exists(remoteFile))
  837. {
  838. client.DeleteFile(remoteFile);
  839. }
  840. }
  841. }
  842. }
  843. [TestMethod]
  844. public void Sftp_AppendText_Encoding_DirectoryDoesNotExist()
  845. {
  846. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  847. var encoding = GetRandomEncoding();
  848. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  849. {
  850. client.Connect();
  851. if (client.Exists(remoteFile))
  852. {
  853. client.DeleteFile(remoteFile);
  854. }
  855. StreamWriter sw = null;
  856. try
  857. {
  858. sw = client.AppendText(remoteFile, encoding);
  859. Assert.Fail();
  860. }
  861. catch (SftpPathNotFoundException ex)
  862. {
  863. Assert.IsNull(ex.InnerException);
  864. Assert.AreEqual("No such file", ex.Message);
  865. }
  866. finally
  867. {
  868. sw?.Dispose();
  869. if (client.Exists(remoteFile))
  870. {
  871. client.DeleteFile(remoteFile);
  872. }
  873. }
  874. }
  875. }
  876. [TestMethod]
  877. public void Sftp_AppendText_Encoding_FileDoesNotExist()
  878. {
  879. var encoding = GetRandomEncoding();
  880. const string contentToAppend = "\u0100ert & Ann";
  881. var expectedBytes = GetBytesWithPreamble(contentToAppend, encoding);
  882. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  883. {
  884. client.Connect();
  885. var remoteFile = GenerateUniqueRemoteFileName();
  886. if (client.Exists(remoteFile))
  887. {
  888. client.DeleteFile(remoteFile);
  889. }
  890. try
  891. {
  892. using (var sw = client.AppendText(remoteFile, encoding))
  893. {
  894. sw.Write(contentToAppend);
  895. }
  896. using (var fs = client.OpenRead(remoteFile))
  897. {
  898. var actualBytes = new byte[fs.Length];
  899. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  900. Assert.IsTrue(expectedBytes.IsEqualTo(actualBytes));
  901. }
  902. }
  903. finally
  904. {
  905. if (client.Exists(remoteFile))
  906. {
  907. client.DeleteFile(remoteFile);
  908. }
  909. }
  910. }
  911. }
  912. [TestMethod]
  913. public void Sftp_CreateText_NoEncoding_ExistingFile()
  914. {
  915. var encoding = new UTF8Encoding(false, true);
  916. const string initialContent = "\u0100ert & Ann";
  917. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  918. const string newContent = "\u0116ver";
  919. const string expectedContent = "\u0116ver" + " & Ann";
  920. var expectedContentBytes = GetBytesWithPreamble(expectedContent, encoding);
  921. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  922. {
  923. client.Connect();
  924. var remoteFile = GenerateUniqueRemoteFileName();
  925. if (client.Exists(remoteFile))
  926. {
  927. client.DeleteFile(remoteFile);
  928. }
  929. try
  930. {
  931. client.WriteAllText(remoteFile, initialContent);
  932. using (client.CreateText(remoteFile))
  933. {
  934. }
  935. // verify that original content is left untouched
  936. using (var fs = client.OpenRead(remoteFile))
  937. {
  938. var actualBytes = new byte[fs.Length];
  939. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  940. Assert.IsTrue(initialContentBytes.IsEqualTo(actualBytes));
  941. }
  942. // write content that is less bytes than original content
  943. using (var sw = client.CreateText(remoteFile))
  944. {
  945. sw.Write(newContent);
  946. }
  947. // verify that original content is only partially overwritten
  948. var text = client.ReadAllText(remoteFile);
  949. Assert.AreEqual(expectedContent, text);
  950. using (var fs = client.OpenRead(remoteFile))
  951. {
  952. var actualBytes = new byte[fs.Length];
  953. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  954. Assert.IsTrue(expectedContentBytes.IsEqualTo(actualBytes));
  955. }
  956. }
  957. finally
  958. {
  959. if (client.Exists(remoteFile))
  960. {
  961. client.DeleteFile(remoteFile);
  962. }
  963. }
  964. }
  965. }
  966. [TestMethod]
  967. public void Sftp_CreateText_NoEncoding_DirectoryDoesNotExist()
  968. {
  969. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  970. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  971. {
  972. client.Connect();
  973. if (client.Exists(remoteFile))
  974. {
  975. client.DeleteFile(remoteFile);
  976. }
  977. StreamWriter sw = null;
  978. try
  979. {
  980. sw = client.CreateText(remoteFile);
  981. Assert.Fail();
  982. }
  983. catch (SftpPathNotFoundException ex)
  984. {
  985. Assert.IsNull(ex.InnerException);
  986. Assert.AreEqual("No such file", ex.Message);
  987. }
  988. finally
  989. {
  990. sw?.Dispose();
  991. if (client.Exists(remoteFile))
  992. {
  993. client.DeleteFile(remoteFile);
  994. }
  995. }
  996. }
  997. }
  998. [TestMethod]
  999. public void Sftp_CreateText_NoEncoding_FileDoesNotExist()
  1000. {
  1001. var encoding = new UTF8Encoding(false, true);
  1002. var initialContent = "\u0100ert & Ann";
  1003. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  1004. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1005. {
  1006. client.Connect();
  1007. var remoteFile = GenerateUniqueRemoteFileName();
  1008. if (client.Exists(remoteFile))
  1009. {
  1010. client.DeleteFile(remoteFile);
  1011. }
  1012. try
  1013. {
  1014. using (client.CreateText(remoteFile))
  1015. {
  1016. }
  1017. // verify that empty file was created
  1018. Assert.IsTrue(client.Exists(remoteFile));
  1019. var file = client.GetAttributes(remoteFile);
  1020. Assert.AreEqual(0, file.Size);
  1021. client.DeleteFile(remoteFile);
  1022. using (var sw = client.CreateText(remoteFile))
  1023. {
  1024. sw.Write(initialContent);
  1025. }
  1026. // verify that content is written to file
  1027. var text = client.ReadAllText(remoteFile);
  1028. Assert.AreEqual(initialContent, text);
  1029. using (var fs = client.OpenRead(remoteFile))
  1030. {
  1031. var actualBytes = new byte[fs.Length];
  1032. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  1033. Assert.IsTrue(initialContentBytes.IsEqualTo(actualBytes));
  1034. }
  1035. }
  1036. finally
  1037. {
  1038. if (client.Exists(remoteFile))
  1039. {
  1040. client.DeleteFile(remoteFile);
  1041. }
  1042. }
  1043. }
  1044. }
  1045. [TestMethod]
  1046. public void Sftp_CreateText_Encoding_ExistingFile()
  1047. {
  1048. var encoding = GetRandomEncoding();
  1049. var initialContent = "\u0100ert & Ann";
  1050. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  1051. var newContent = "\u0116ver";
  1052. var expectedContent = "\u0116ver" + " & Ann";
  1053. var expectedContentBytes = GetBytesWithPreamble(expectedContent, encoding);
  1054. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1055. {
  1056. client.Connect();
  1057. var remoteFile = GenerateUniqueRemoteFileName();
  1058. if (client.Exists(remoteFile))
  1059. {
  1060. client.DeleteFile(remoteFile);
  1061. }
  1062. try
  1063. {
  1064. client.WriteAllText(remoteFile, initialContent, encoding);
  1065. using (client.CreateText(remoteFile))
  1066. {
  1067. }
  1068. // verify that original content is left untouched
  1069. using (var fs = client.OpenRead(remoteFile))
  1070. {
  1071. var actualBytes = new byte[fs.Length];
  1072. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  1073. Assert.IsTrue(initialContentBytes.IsEqualTo(actualBytes));
  1074. }
  1075. // write content that is less bytes than original content
  1076. using (var sw = client.CreateText(remoteFile, encoding))
  1077. {
  1078. sw.Write(newContent);
  1079. }
  1080. // verify that original content is only partially overwritten
  1081. var text = client.ReadAllText(remoteFile, encoding);
  1082. Assert.AreEqual(expectedContent, text);
  1083. using (var fs = client.OpenRead(remoteFile))
  1084. {
  1085. var actualBytes = new byte[fs.Length];
  1086. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  1087. Assert.IsTrue(expectedContentBytes.IsEqualTo(actualBytes));
  1088. }
  1089. }
  1090. finally
  1091. {
  1092. if (client.Exists(remoteFile))
  1093. {
  1094. client.DeleteFile(remoteFile);
  1095. }
  1096. }
  1097. }
  1098. }
  1099. [TestMethod]
  1100. public void Sftp_CreateText_Encoding_DirectoryDoesNotExist()
  1101. {
  1102. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  1103. var encoding = GetRandomEncoding();
  1104. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1105. {
  1106. client.Connect();
  1107. if (client.Exists(remoteFile))
  1108. {
  1109. client.DeleteFile(remoteFile);
  1110. }
  1111. StreamWriter sw = null;
  1112. try
  1113. {
  1114. sw = client.CreateText(remoteFile, encoding);
  1115. Assert.Fail();
  1116. }
  1117. catch (SftpPathNotFoundException ex)
  1118. {
  1119. Assert.IsNull(ex.InnerException);
  1120. Assert.AreEqual("No such file", ex.Message);
  1121. }
  1122. finally
  1123. {
  1124. sw?.Dispose();
  1125. if (client.Exists(remoteFile))
  1126. {
  1127. client.DeleteFile(remoteFile);
  1128. }
  1129. }
  1130. }
  1131. }
  1132. [TestMethod]
  1133. public void Sftp_CreateText_Encoding_FileDoesNotExist()
  1134. {
  1135. var encoding = GetRandomEncoding();
  1136. var initialContent = "\u0100ert & Ann";
  1137. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  1138. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1139. {
  1140. client.Connect();
  1141. var remoteFile = GenerateUniqueRemoteFileName();
  1142. if (client.Exists(remoteFile))
  1143. {
  1144. client.DeleteFile(remoteFile);
  1145. }
  1146. try
  1147. {
  1148. using (client.CreateText(remoteFile, encoding))
  1149. {
  1150. }
  1151. // verify that file containing only preamble was created
  1152. Assert.IsTrue(client.Exists(remoteFile));
  1153. var file = client.GetAttributes(remoteFile);
  1154. Assert.AreEqual(encoding.GetPreamble().Length, file.Size);
  1155. client.DeleteFile(remoteFile);
  1156. using (var sw = client.CreateText(remoteFile, encoding))
  1157. {
  1158. sw.Write(initialContent);
  1159. }
  1160. // verify that content is written to file
  1161. var text = client.ReadAllText(remoteFile, encoding);
  1162. Assert.AreEqual(initialContent, text);
  1163. using (var fs = client.OpenRead(remoteFile))
  1164. {
  1165. var actualBytes = new byte[fs.Length];
  1166. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  1167. Assert.IsTrue(initialContentBytes.IsEqualTo(actualBytes));
  1168. }
  1169. }
  1170. finally
  1171. {
  1172. if (client.Exists(remoteFile))
  1173. {
  1174. client.DeleteFile(remoteFile);
  1175. }
  1176. }
  1177. }
  1178. }
  1179. [TestMethod]
  1180. public void Sftp_DownloadFile_FileDoesNotExist()
  1181. {
  1182. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1183. {
  1184. client.Connect();
  1185. var remoteFile = GenerateUniqueRemoteFileName();
  1186. if (client.Exists(remoteFile))
  1187. {
  1188. client.DeleteFile(remoteFile);
  1189. }
  1190. using (var ms = new MemoryStream())
  1191. {
  1192. try
  1193. {
  1194. client.DownloadFile(remoteFile, ms);
  1195. Assert.Fail();
  1196. }
  1197. catch (SftpPathNotFoundException ex)
  1198. {
  1199. Assert.IsNull(ex.InnerException);
  1200. Assert.AreEqual("No such file", ex.Message);
  1201. // ensure file was not created by us
  1202. Assert.IsFalse(client.Exists(remoteFile));
  1203. }
  1204. finally
  1205. {
  1206. if (client.Exists(remoteFile))
  1207. {
  1208. client.DeleteFile(remoteFile);
  1209. }
  1210. }
  1211. }
  1212. }
  1213. }
  1214. [TestMethod]
  1215. public void Sftp_ReadAllBytes_ExistingFile()
  1216. {
  1217. var encoding = GetRandomEncoding();
  1218. var content = "\u0100ert & Ann";
  1219. var contentBytes = GetBytesWithPreamble(content, encoding);
  1220. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1221. {
  1222. client.Connect();
  1223. var remoteFile = GenerateUniqueRemoteFileName();
  1224. if (client.Exists(remoteFile))
  1225. {
  1226. client.DeleteFile(remoteFile);
  1227. }
  1228. try
  1229. {
  1230. client.WriteAllText(remoteFile, content, encoding);
  1231. var actualBytes = client.ReadAllBytes(remoteFile);
  1232. Assert.IsTrue(contentBytes.IsEqualTo(actualBytes));
  1233. }
  1234. finally
  1235. {
  1236. if (client.Exists(remoteFile))
  1237. {
  1238. client.DeleteFile(remoteFile);
  1239. }
  1240. }
  1241. }
  1242. }
  1243. [TestMethod]
  1244. public void Sftp_ReadAllBytes_FileDoesNotExist()
  1245. {
  1246. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1247. {
  1248. client.Connect();
  1249. var remoteFile = GenerateUniqueRemoteFileName();
  1250. if (client.Exists(remoteFile))
  1251. {
  1252. client.DeleteFile(remoteFile);
  1253. }
  1254. try
  1255. {
  1256. client.ReadAllBytes(remoteFile);
  1257. Assert.Fail();
  1258. }
  1259. catch (SftpPathNotFoundException ex)
  1260. {
  1261. Assert.IsNull(ex.InnerException);
  1262. Assert.AreEqual("No such file", ex.Message);
  1263. // ensure file was not created by us
  1264. Assert.IsFalse(client.Exists(remoteFile));
  1265. }
  1266. finally
  1267. {
  1268. if (client.Exists(remoteFile))
  1269. {
  1270. client.DeleteFile(remoteFile);
  1271. }
  1272. }
  1273. }
  1274. }
  1275. [TestMethod]
  1276. public void Sftp_ReadAllLines_NoEncoding_ExistingFile()
  1277. {
  1278. var encoding = new UTF8Encoding(false, true);
  1279. var lines = new[] { "\u0100ert & Ann", "Forever", "&", "\u0116ver" };
  1280. var linesBytes = GetBytesWithPreamble(string.Join(Environment.NewLine, lines) + Environment.NewLine,
  1281. encoding);
  1282. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1283. {
  1284. client.Connect();
  1285. var remoteFile = GenerateUniqueRemoteFileName();
  1286. if (client.Exists(remoteFile))
  1287. {
  1288. client.DeleteFile(remoteFile);
  1289. }
  1290. try
  1291. {
  1292. using (var sw = client.AppendText(remoteFile))
  1293. {
  1294. for (var i = 0; i < lines.Length; i++)
  1295. {
  1296. sw.WriteLine(lines[i]);
  1297. }
  1298. }
  1299. var actualLines = client.ReadAllLines(remoteFile);
  1300. Assert.IsNotNull(actualLines);
  1301. Assert.AreEqual(lines.Length, actualLines.Length);
  1302. for (var i = 0; i < lines.Length; i++)
  1303. {
  1304. Assert.AreEqual(lines[i], actualLines[i]);
  1305. }
  1306. using (var fs = client.OpenRead(remoteFile))
  1307. {
  1308. var actualBytes = new byte[fs.Length];
  1309. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  1310. Assert.IsTrue(linesBytes.IsEqualTo(actualBytes));
  1311. }
  1312. }
  1313. finally
  1314. {
  1315. if (client.Exists(remoteFile))
  1316. {
  1317. client.DeleteFile(remoteFile);
  1318. }
  1319. }
  1320. }
  1321. }
  1322. [TestMethod]
  1323. public void Sftp_ReadAllLines_NoEncoding_FileDoesNotExist()
  1324. {
  1325. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1326. {
  1327. client.Connect();
  1328. var remoteFile = GenerateUniqueRemoteFileName();
  1329. if (client.Exists(remoteFile))
  1330. {
  1331. client.DeleteFile(remoteFile);
  1332. }
  1333. try
  1334. {
  1335. client.ReadAllLines(remoteFile);
  1336. Assert.Fail();
  1337. }
  1338. catch (SftpPathNotFoundException ex)
  1339. {
  1340. Assert.IsNull(ex.InnerException);
  1341. Assert.AreEqual("No such file", ex.Message);
  1342. // ensure file was not created by us
  1343. Assert.IsFalse(client.Exists(remoteFile));
  1344. }
  1345. finally
  1346. {
  1347. if (client.Exists(remoteFile))
  1348. {
  1349. client.DeleteFile(remoteFile);
  1350. }
  1351. }
  1352. }
  1353. }
  1354. [TestMethod]
  1355. public void Sftp_ReadAllLines_Encoding_ExistingFile()
  1356. {
  1357. var encoding = GetRandomEncoding();
  1358. var lines = new[] { "\u0100ert & Ann", "Forever", "&", "\u0116ver" };
  1359. var linesBytes = GetBytesWithPreamble(string.Join(Environment.NewLine, lines) + Environment.NewLine,
  1360. encoding);
  1361. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1362. {
  1363. client.Connect();
  1364. var remoteFile = GenerateUniqueRemoteFileName();
  1365. if (client.Exists(remoteFile))
  1366. {
  1367. client.DeleteFile(remoteFile);
  1368. }
  1369. try
  1370. {
  1371. using (var sw = client.AppendText(remoteFile, encoding))
  1372. {
  1373. for (var i = 0; i < lines.Length; i++)
  1374. {
  1375. sw.WriteLine(lines[i]);
  1376. }
  1377. }
  1378. var actualLines = client.ReadAllLines(remoteFile, encoding);
  1379. Assert.IsNotNull(actualLines);
  1380. Assert.AreEqual(lines.Length, actualLines.Length);
  1381. for (var i = 0; i < lines.Length; i++)
  1382. {
  1383. Assert.AreEqual(lines[i], actualLines[i]);
  1384. }
  1385. using (var fs = client.OpenRead(remoteFile))
  1386. {
  1387. var actualBytes = new byte[fs.Length];
  1388. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  1389. Assert.IsTrue(linesBytes.IsEqualTo(actualBytes));
  1390. }
  1391. }
  1392. finally
  1393. {
  1394. if (client.Exists(remoteFile))
  1395. {
  1396. client.DeleteFile(remoteFile);
  1397. }
  1398. }
  1399. }
  1400. }
  1401. [TestMethod]
  1402. public void Sftp_ReadAllLines_Encoding_FileDoesNotExist()
  1403. {
  1404. var encoding = GetRandomEncoding();
  1405. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1406. {
  1407. client.Connect();
  1408. var remoteFile = GenerateUniqueRemoteFileName();
  1409. if (client.Exists(remoteFile))
  1410. {
  1411. client.DeleteFile(remoteFile);
  1412. }
  1413. try
  1414. {
  1415. client.ReadAllLines(remoteFile, encoding);
  1416. Assert.Fail();
  1417. }
  1418. catch (SftpPathNotFoundException ex)
  1419. {
  1420. Assert.IsNull(ex.InnerException);
  1421. Assert.AreEqual("No such file", ex.Message);
  1422. // ensure file was not created by us
  1423. Assert.IsFalse(client.Exists(remoteFile));
  1424. }
  1425. finally
  1426. {
  1427. if (client.Exists(remoteFile))
  1428. {
  1429. client.DeleteFile(remoteFile);
  1430. }
  1431. }
  1432. }
  1433. }
  1434. [TestMethod]
  1435. public void Sftp_ReadAllText_NoEncoding_ExistingFile()
  1436. {
  1437. var encoding = new UTF8Encoding(false, true);
  1438. var lines = new[] { "\u0100ert & Ann", "Forever", "&", "\u0116ver" };
  1439. var expectedText = string.Join(Environment.NewLine, lines) + Environment.NewLine;
  1440. var expectedBytes = GetBytesWithPreamble(expectedText, encoding);
  1441. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1442. {
  1443. client.Connect();
  1444. var remoteFile = GenerateUniqueRemoteFileName();
  1445. if (client.Exists(remoteFile))
  1446. {
  1447. client.DeleteFile(remoteFile);
  1448. }
  1449. try
  1450. {
  1451. using (var sw = client.AppendText(remoteFile))
  1452. {
  1453. for (var i = 0; i < lines.Length; i++)
  1454. {
  1455. sw.WriteLine(lines[i]);
  1456. }
  1457. }
  1458. var actualText = client.ReadAllText(remoteFile);
  1459. Assert.AreEqual(actualText, expectedText);
  1460. using (var fs = client.OpenRead(remoteFile))
  1461. {
  1462. var actualBytes = new byte[fs.Length];
  1463. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  1464. Assert.IsTrue(expectedBytes.IsEqualTo(actualBytes));
  1465. }
  1466. }
  1467. finally
  1468. {
  1469. if (client.Exists(remoteFile))
  1470. {
  1471. client.DeleteFile(remoteFile);
  1472. }
  1473. }
  1474. }
  1475. }
  1476. [TestMethod]
  1477. public void Sftp_ReadAllText_NoEncoding_FileDoesNotExist()
  1478. {
  1479. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1480. {
  1481. client.Connect();
  1482. var remoteFile = GenerateUniqueRemoteFileName();
  1483. if (client.Exists(remoteFile))
  1484. {
  1485. client.DeleteFile(remoteFile);
  1486. }
  1487. try
  1488. {
  1489. client.ReadAllText(remoteFile);
  1490. Assert.Fail();
  1491. }
  1492. catch (SftpPathNotFoundException ex)
  1493. {
  1494. Assert.IsNull(ex.InnerException);
  1495. Assert.AreEqual("No such file", ex.Message);
  1496. // ensure file was not created by us
  1497. Assert.IsFalse(client.Exists(remoteFile));
  1498. }
  1499. finally
  1500. {
  1501. if (client.Exists(remoteFile))
  1502. {
  1503. client.DeleteFile(remoteFile);
  1504. }
  1505. }
  1506. }
  1507. }
  1508. [TestMethod]
  1509. public void Sftp_ReadAllText_Encoding_ExistingFile()
  1510. {
  1511. var encoding = GetRandomEncoding();
  1512. var lines = new[] { "\u0100ert & Ann", "Forever", "&", "\u0116ver" };
  1513. var expectedText = string.Join(Environment.NewLine, lines) + Environment.NewLine;
  1514. var expectedBytes = GetBytesWithPreamble(expectedText, encoding);
  1515. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1516. {
  1517. client.Connect();
  1518. var remoteFile = GenerateUniqueRemoteFileName();
  1519. if (client.Exists(remoteFile))
  1520. {
  1521. client.DeleteFile(remoteFile);
  1522. }
  1523. try
  1524. {
  1525. using (var sw = client.AppendText(remoteFile, encoding))
  1526. {
  1527. for (var i = 0; i < lines.Length; i++)
  1528. {
  1529. sw.WriteLine(lines[i]);
  1530. }
  1531. }
  1532. var actualText = client.ReadAllText(remoteFile, encoding);
  1533. Assert.AreEqual(expectedText, actualText);
  1534. using (var fs = client.OpenRead(remoteFile))
  1535. {
  1536. var actualBytes = new byte[fs.Length];
  1537. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  1538. Assert.IsTrue(expectedBytes.IsEqualTo(actualBytes));
  1539. }
  1540. }
  1541. finally
  1542. {
  1543. if (client.Exists(remoteFile))
  1544. {
  1545. client.DeleteFile(remoteFile);
  1546. }
  1547. }
  1548. }
  1549. }
  1550. [TestMethod]
  1551. public void Sftp_ReadAllText_Encoding_FileDoesNotExist()
  1552. {
  1553. var encoding = GetRandomEncoding();
  1554. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1555. {
  1556. client.Connect();
  1557. var remoteFile = GenerateUniqueRemoteFileName();
  1558. if (client.Exists(remoteFile))
  1559. {
  1560. client.DeleteFile(remoteFile);
  1561. }
  1562. try
  1563. {
  1564. client.ReadAllText(remoteFile, encoding);
  1565. Assert.Fail();
  1566. }
  1567. catch (SftpPathNotFoundException ex)
  1568. {
  1569. Assert.IsNull(ex.InnerException);
  1570. Assert.AreEqual("No such file", ex.Message);
  1571. // ensure file was not created by us
  1572. Assert.IsFalse(client.Exists(remoteFile));
  1573. }
  1574. finally
  1575. {
  1576. if (client.Exists(remoteFile))
  1577. {
  1578. client.DeleteFile(remoteFile);
  1579. }
  1580. }
  1581. }
  1582. }
  1583. [TestMethod]
  1584. public void Sftp_ReadLines_NoEncoding_ExistingFile()
  1585. {
  1586. var lines = new[] { "\u0100ert & Ann", "Forever", "&", "\u0116ver" };
  1587. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1588. {
  1589. client.Connect();
  1590. var remoteFile = GenerateUniqueRemoteFileName();
  1591. if (client.Exists(remoteFile))
  1592. {
  1593. client.DeleteFile(remoteFile);
  1594. }
  1595. try
  1596. {
  1597. using (var sw = client.AppendText(remoteFile))
  1598. {
  1599. for (var i = 0; i < lines.Length; i++)
  1600. {
  1601. sw.WriteLine(lines[i]);
  1602. }
  1603. }
  1604. var actualLines = client.ReadLines(remoteFile);
  1605. Assert.IsNotNull(actualLines);
  1606. var actualLinesEnum = actualLines.GetEnumerator();
  1607. for (var i = 0; i < lines.Length; i++)
  1608. {
  1609. Assert.IsTrue(actualLinesEnum.MoveNext());
  1610. var actualLine = actualLinesEnum.Current;
  1611. Assert.AreEqual(lines[i], actualLine);
  1612. }
  1613. Assert.IsFalse(actualLinesEnum.MoveNext());
  1614. }
  1615. finally
  1616. {
  1617. if (client.Exists(remoteFile))
  1618. {
  1619. client.DeleteFile(remoteFile);
  1620. }
  1621. }
  1622. }
  1623. }
  1624. [TestMethod]
  1625. public void Sftp_ReadLines_NoEncoding_FileDoesNotExist()
  1626. {
  1627. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1628. {
  1629. client.Connect();
  1630. var remoteFile = GenerateUniqueRemoteFileName();
  1631. if (client.Exists(remoteFile))
  1632. {
  1633. client.DeleteFile(remoteFile);
  1634. }
  1635. try
  1636. {
  1637. client.ReadLines(remoteFile);
  1638. Assert.Fail();
  1639. }
  1640. catch (SftpPathNotFoundException ex)
  1641. {
  1642. Assert.IsNull(ex.InnerException);
  1643. Assert.AreEqual("No such file", ex.Message);
  1644. // ensure file was not created by us
  1645. Assert.IsFalse(client.Exists(remoteFile));
  1646. }
  1647. finally
  1648. {
  1649. if (client.Exists(remoteFile))
  1650. {
  1651. client.DeleteFile(remoteFile);
  1652. }
  1653. }
  1654. }
  1655. }
  1656. [TestMethod]
  1657. public void Sftp_ReadLines_Encoding_ExistingFile()
  1658. {
  1659. var encoding = GetRandomEncoding();
  1660. var lines = new[] { "\u0100ert & Ann", "Forever", "&", "\u0116ver" };
  1661. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1662. {
  1663. client.Connect();
  1664. var remoteFile = GenerateUniqueRemoteFileName();
  1665. if (client.Exists(remoteFile))
  1666. {
  1667. client.DeleteFile(remoteFile);
  1668. }
  1669. try
  1670. {
  1671. using (var sw = client.AppendText(remoteFile, encoding))
  1672. {
  1673. for (var i = 0; i < lines.Length; i++)
  1674. {
  1675. sw.WriteLine(lines[i]);
  1676. }
  1677. }
  1678. var actualLines = client.ReadLines(remoteFile, encoding);
  1679. Assert.IsNotNull(actualLines);
  1680. using (var actualLinesEnum = actualLines.GetEnumerator())
  1681. {
  1682. for (var i = 0; i < lines.Length; i++)
  1683. {
  1684. Assert.IsTrue(actualLinesEnum.MoveNext());
  1685. var actualLine = actualLinesEnum.Current;
  1686. Assert.AreEqual(lines[i], actualLine);
  1687. }
  1688. Assert.IsFalse(actualLinesEnum.MoveNext());
  1689. }
  1690. }
  1691. finally
  1692. {
  1693. if (client.Exists(remoteFile))
  1694. {
  1695. client.DeleteFile(remoteFile);
  1696. }
  1697. }
  1698. }
  1699. }
  1700. [TestMethod]
  1701. public void Sftp_ReadLines_Encoding_FileDoesNotExist()
  1702. {
  1703. var encoding = GetRandomEncoding();
  1704. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1705. {
  1706. client.Connect();
  1707. var remoteFile = GenerateUniqueRemoteFileName();
  1708. if (client.Exists(remoteFile))
  1709. {
  1710. client.DeleteFile(remoteFile);
  1711. }
  1712. try
  1713. {
  1714. client.ReadLines(remoteFile, encoding);
  1715. Assert.Fail();
  1716. }
  1717. catch (SftpPathNotFoundException ex)
  1718. {
  1719. Assert.IsNull(ex.InnerException);
  1720. Assert.AreEqual("No such file", ex.Message);
  1721. // ensure file was not created by us
  1722. Assert.IsFalse(client.Exists(remoteFile));
  1723. }
  1724. finally
  1725. {
  1726. if (client.Exists(remoteFile))
  1727. {
  1728. client.DeleteFile(remoteFile);
  1729. }
  1730. }
  1731. }
  1732. }
  1733. [TestMethod]
  1734. public void Sftp_WriteAllBytes_DirectoryDoesNotExist()
  1735. {
  1736. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  1737. var content = GenerateRandom(size: 5);
  1738. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1739. {
  1740. client.Connect();
  1741. if (client.Exists(remoteFile))
  1742. {
  1743. client.DeleteFile(remoteFile);
  1744. }
  1745. try
  1746. {
  1747. client.WriteAllBytes(remoteFile, content);
  1748. Assert.Fail();
  1749. }
  1750. catch (SftpPathNotFoundException ex)
  1751. {
  1752. Assert.IsNull(ex.InnerException);
  1753. Assert.AreEqual("No such file", ex.Message);
  1754. }
  1755. finally
  1756. {
  1757. if (client.Exists(remoteFile))
  1758. {
  1759. client.DeleteFile(remoteFile);
  1760. }
  1761. }
  1762. }
  1763. }
  1764. [TestMethod]
  1765. public void Sftp_WriteAllBytes_ExistingFile()
  1766. {
  1767. var initialContent = GenerateRandom(size: 13);
  1768. var newContent1 = GenerateRandom(size: 5);
  1769. var expectedContent1 = new ArrayBuilder<byte>().Add(newContent1)
  1770. .Add(initialContent, newContent1.Length, initialContent.Length - newContent1.Length)
  1771. .Build();
  1772. var newContent2 = GenerateRandom(size: 50000);
  1773. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1774. {
  1775. client.Connect();
  1776. var remoteFile = GenerateUniqueRemoteFileName();
  1777. if (client.Exists(remoteFile))
  1778. {
  1779. client.DeleteFile(remoteFile);
  1780. }
  1781. try
  1782. {
  1783. using (var fs = client.Create(remoteFile))
  1784. {
  1785. fs.Write(initialContent, offset: 0, initialContent.Length);
  1786. }
  1787. #region Write less bytes than the current content, overwriting part of that content
  1788. client.WriteAllBytes(remoteFile, newContent1);
  1789. var actualContent1 = client.ReadAllBytes(remoteFile);
  1790. Assert.IsTrue(expectedContent1.IsEqualTo(actualContent1));
  1791. #endregion Write less bytes than the initial content, overwriting part of that content
  1792. #region Write more bytes than the current content, overwriting and appending to that content
  1793. client.WriteAllBytes(remoteFile, newContent2);
  1794. var actualContent2 = client.ReadAllBytes(remoteFile);
  1795. Assert.IsTrue(newContent2.IsEqualTo(actualContent2));
  1796. #endregion Write less bytes than the initial content, overwriting part of that content
  1797. }
  1798. finally
  1799. {
  1800. if (client.Exists(remoteFile))
  1801. {
  1802. client.DeleteFile(remoteFile);
  1803. }
  1804. }
  1805. }
  1806. }
  1807. [TestMethod]
  1808. public void Sftp_WriteAllBytes_FileDoesNotExist()
  1809. {
  1810. var content = GenerateRandom(size: 13);
  1811. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1812. {
  1813. client.Connect();
  1814. var remoteFile = GenerateUniqueRemoteFileName();
  1815. if (client.Exists(remoteFile))
  1816. {
  1817. client.DeleteFile(remoteFile);
  1818. }
  1819. try
  1820. {
  1821. client.WriteAllBytes(remoteFile, content);
  1822. using (var fs = client.OpenRead(remoteFile))
  1823. {
  1824. var actualBytes = new byte[fs.Length];
  1825. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  1826. Assert.IsTrue(content.IsEqualTo(actualBytes));
  1827. }
  1828. }
  1829. finally
  1830. {
  1831. if (client.Exists(remoteFile))
  1832. {
  1833. client.DeleteFile(remoteFile);
  1834. }
  1835. }
  1836. }
  1837. }
  1838. [TestMethod]
  1839. public void Sftp_WriteAllLines_IEnumerable_NoEncoding_DirectoryDoesNotExist()
  1840. {
  1841. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  1842. IEnumerable<string> linesToWrite = new[] { "Forever", "&", "\u0116ver" };
  1843. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1844. {
  1845. client.Connect();
  1846. if (client.Exists(remoteFile))
  1847. {
  1848. client.DeleteFile(remoteFile);
  1849. }
  1850. try
  1851. {
  1852. client.WriteAllLines(remoteFile, linesToWrite);
  1853. Assert.Fail();
  1854. }
  1855. catch (SftpPathNotFoundException ex)
  1856. {
  1857. Assert.IsNull(ex.InnerException);
  1858. Assert.AreEqual("No such file", ex.Message);
  1859. }
  1860. finally
  1861. {
  1862. if (client.Exists(remoteFile))
  1863. {
  1864. client.DeleteFile(remoteFile);
  1865. }
  1866. }
  1867. }
  1868. }
  1869. [TestMethod]
  1870. public void Sftp_WriteAllLines_IEnumerable_NoEncoding_ExistingFile()
  1871. {
  1872. var encoding = new UTF8Encoding(false, true);
  1873. var initialContent = "\u0100ert & Ann Forever & Ever Lisa & Sofie";
  1874. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  1875. IEnumerable<string> linesToWrite1 = new[] { "Forever", "&", "\u0116ver" };
  1876. var linesToWrite1Bytes =
  1877. GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite1) + Environment.NewLine, encoding);
  1878. var expectedBytes1 = new ArrayBuilder<byte>().Add(linesToWrite1Bytes)
  1879. .Add(initialContentBytes,
  1880. linesToWrite1Bytes.Length,
  1881. initialContentBytes.Length - linesToWrite1Bytes.Length)
  1882. .Build();
  1883. IEnumerable<string> linesToWrite2 = new[] { "Forever", "&", "\u0116ver", "Gert & Ann", "Lisa + Sofie" };
  1884. var linesToWrite2Bytes =
  1885. GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite2) + Environment.NewLine, encoding);
  1886. var expectedBytes2 = linesToWrite2Bytes;
  1887. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1888. {
  1889. client.Connect();
  1890. var remoteFile = GenerateUniqueRemoteFileName();
  1891. if (client.Exists(remoteFile))
  1892. {
  1893. client.DeleteFile(remoteFile);
  1894. }
  1895. try
  1896. {
  1897. // create initial content
  1898. client.WriteAllText(remoteFile, initialContent);
  1899. #region Write less bytes than the current content, overwriting part of that content
  1900. client.WriteAllLines(remoteFile, linesToWrite1);
  1901. using (var fs = client.OpenRead(remoteFile))
  1902. {
  1903. var actualBytes = new byte[fs.Length];
  1904. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  1905. Assert.IsTrue(expectedBytes1.IsEqualTo(actualBytes));
  1906. }
  1907. #endregion Write less bytes than the current content, overwriting part of that content
  1908. #region Write more bytes than the current content, overwriting and appending to that content
  1909. client.WriteAllLines(remoteFile, linesToWrite2);
  1910. using (var fs = client.OpenRead(remoteFile))
  1911. {
  1912. var actualBytes = new byte[fs.Length];
  1913. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  1914. Assert.IsTrue(expectedBytes2.IsEqualTo(actualBytes));
  1915. }
  1916. #endregion Write more bytes than the current content, overwriting and appending to that content
  1917. }
  1918. finally
  1919. {
  1920. if (client.Exists(remoteFile))
  1921. {
  1922. client.DeleteFile(remoteFile);
  1923. }
  1924. }
  1925. }
  1926. }
  1927. [TestMethod]
  1928. public void Sftp_WriteAllLines_IEnumerable_NoEncoding_FileDoesNotExist()
  1929. {
  1930. var encoding = new UTF8Encoding(false, true);
  1931. IEnumerable<string> linesToWrite = new[] { "\u0139isa", "&", "Sofie" };
  1932. var linesToWriteBytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite) + Environment.NewLine, encoding);
  1933. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1934. {
  1935. client.Connect();
  1936. var remoteFile = GenerateUniqueRemoteFileName();
  1937. if (client.Exists(remoteFile))
  1938. {
  1939. client.DeleteFile(remoteFile);
  1940. }
  1941. try
  1942. {
  1943. client.WriteAllLines(remoteFile, linesToWrite);
  1944. using (var fs = client.OpenRead(remoteFile))
  1945. {
  1946. var actualBytes = new byte[fs.Length];
  1947. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  1948. Assert.IsTrue(linesToWriteBytes.IsEqualTo(actualBytes));
  1949. }
  1950. }
  1951. finally
  1952. {
  1953. if (client.Exists(remoteFile))
  1954. {
  1955. client.DeleteFile(remoteFile);
  1956. }
  1957. }
  1958. }
  1959. }
  1960. [TestMethod]
  1961. public void Sftp_WriteAllLines_IEnumerable_Encoding_DirectoryDoesNotExist()
  1962. {
  1963. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  1964. var encoding = GetRandomEncoding();
  1965. IEnumerable<string> linesToWrite = new[] { "Forever", "&", "\u0116ver" };
  1966. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1967. {
  1968. client.Connect();
  1969. if (client.Exists(remoteFile))
  1970. {
  1971. client.DeleteFile(remoteFile);
  1972. }
  1973. try
  1974. {
  1975. client.WriteAllLines(remoteFile, linesToWrite, encoding);
  1976. Assert.Fail();
  1977. }
  1978. catch (SftpPathNotFoundException ex)
  1979. {
  1980. Assert.IsNull(ex.InnerException);
  1981. Assert.AreEqual("No such file", ex.Message);
  1982. }
  1983. finally
  1984. {
  1985. if (client.Exists(remoteFile))
  1986. {
  1987. client.DeleteFile(remoteFile);
  1988. }
  1989. }
  1990. }
  1991. }
  1992. [TestMethod]
  1993. public void Sftp_WriteAllLines_IEnumerable_Encoding_ExistingFile()
  1994. {
  1995. var encoding = GetRandomEncoding();
  1996. const string initialContent = "\u0100ert & Ann Forever & Ever Lisa & Sofie";
  1997. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  1998. IEnumerable<string> linesToWrite1 = new[] { "Forever", "&", "\u0116ver" };
  1999. var linesToWrite1Bytes =
  2000. GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite1) + Environment.NewLine, encoding);
  2001. var expectedBytes1 = new ArrayBuilder<byte>().Add(linesToWrite1Bytes)
  2002. .Add(initialContentBytes,
  2003. linesToWrite1Bytes.Length,
  2004. initialContentBytes.Length - linesToWrite1Bytes.Length)
  2005. .Build();
  2006. IEnumerable<string> linesToWrite2 = new[] { "Forever", "&", "\u0116ver", "Gert & Ann", "Lisa + Sofie" };
  2007. var linesToWrite2Bytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite2) + Environment.NewLine, encoding);
  2008. var expectedBytes2 = linesToWrite2Bytes;
  2009. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2010. {
  2011. client.Connect();
  2012. var remoteFile = GenerateUniqueRemoteFileName();
  2013. if (client.Exists(remoteFile))
  2014. {
  2015. client.DeleteFile(remoteFile);
  2016. }
  2017. try
  2018. {
  2019. // create initial content
  2020. client.WriteAllText(remoteFile, initialContent, encoding);
  2021. #region Write less bytes than the current content, overwriting part of that content
  2022. client.WriteAllLines(remoteFile, linesToWrite1, encoding);
  2023. using (var fs = client.OpenRead(remoteFile))
  2024. {
  2025. var actualBytes = new byte[fs.Length];
  2026. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2027. Assert.IsTrue(expectedBytes1.IsEqualTo(actualBytes));
  2028. }
  2029. #endregion Write less bytes than the current content, overwriting part of that content
  2030. #region Write more bytes than the current content, overwriting and appending to that content
  2031. client.WriteAllLines(remoteFile, linesToWrite2, encoding);
  2032. using (var fs = client.OpenRead(remoteFile))
  2033. {
  2034. var actualBytes = new byte[fs.Length];
  2035. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2036. Assert.IsTrue(expectedBytes2.IsEqualTo(actualBytes));
  2037. }
  2038. #endregion Write more bytes than the current content, overwriting and appending to that content
  2039. }
  2040. finally
  2041. {
  2042. if (client.Exists(remoteFile))
  2043. {
  2044. client.DeleteFile(remoteFile);
  2045. }
  2046. }
  2047. }
  2048. }
  2049. [TestMethod]
  2050. public void Sftp_WriteAllLines_IEnumerable_Encoding_FileDoesNotExist()
  2051. {
  2052. var encoding = GetRandomEncoding();
  2053. IEnumerable<string> linesToWrite = new[] { "\u0139isa", "&", "Sofie" };
  2054. var linesToWriteBytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite) + Environment.NewLine, encoding);
  2055. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2056. {
  2057. client.Connect();
  2058. var remoteFile = GenerateUniqueRemoteFileName();
  2059. if (client.Exists(remoteFile))
  2060. {
  2061. client.DeleteFile(remoteFile);
  2062. }
  2063. try
  2064. {
  2065. client.WriteAllLines(remoteFile, linesToWrite, encoding);
  2066. using (var fs = client.OpenRead(remoteFile))
  2067. {
  2068. var actualBytes = new byte[fs.Length];
  2069. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2070. Assert.IsTrue(linesToWriteBytes.IsEqualTo(actualBytes));
  2071. }
  2072. }
  2073. finally
  2074. {
  2075. if (client.Exists(remoteFile))
  2076. {
  2077. client.DeleteFile(remoteFile);
  2078. }
  2079. }
  2080. }
  2081. }
  2082. [TestMethod]
  2083. public void Sftp_WriteAllLines_Array_NoEncoding_DirectoryDoesNotExist()
  2084. {
  2085. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  2086. var linesToWrite = new[] { "Forever", "&", "\u0116ver" };
  2087. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2088. {
  2089. client.Connect();
  2090. if (client.Exists(remoteFile))
  2091. {
  2092. client.DeleteFile(remoteFile);
  2093. }
  2094. try
  2095. {
  2096. client.WriteAllLines(remoteFile, linesToWrite);
  2097. Assert.Fail();
  2098. }
  2099. catch (SftpPathNotFoundException ex)
  2100. {
  2101. Assert.IsNull(ex.InnerException);
  2102. Assert.AreEqual("No such file", ex.Message);
  2103. }
  2104. finally
  2105. {
  2106. if (client.Exists(remoteFile))
  2107. {
  2108. client.DeleteFile(remoteFile);
  2109. }
  2110. }
  2111. }
  2112. }
  2113. [TestMethod]
  2114. public void Sftp_WriteAllLines_Array_NoEncoding_ExistingFile()
  2115. {
  2116. var encoding = new UTF8Encoding(false, true);
  2117. const string initialContent = "\u0100ert & Ann Forever & Ever Lisa & Sofie";
  2118. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  2119. var linesToWrite1 = new[] { "Forever", "&", "\u0116ver" };
  2120. var linesToWrite1Bytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite1) + Environment.NewLine, encoding);
  2121. var expectedBytes1 = new ArrayBuilder<byte>().Add(linesToWrite1Bytes)
  2122. .Add(initialContentBytes, linesToWrite1Bytes.Length, initialContentBytes.Length - linesToWrite1Bytes.Length)
  2123. .Build();
  2124. var linesToWrite2 = new[] { "Forever", "&", "\u0116ver", "Gert & Ann", "Lisa + Sofie" };
  2125. var linesToWrite2Bytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite2) + Environment.NewLine, encoding);
  2126. var expectedBytes2 = linesToWrite2Bytes;
  2127. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2128. {
  2129. client.Connect();
  2130. var remoteFile = GenerateUniqueRemoteFileName();
  2131. if (client.Exists(remoteFile))
  2132. {
  2133. client.DeleteFile(remoteFile);
  2134. }
  2135. try
  2136. {
  2137. // create initial content
  2138. client.WriteAllText(remoteFile, initialContent);
  2139. #region Write less bytes than the current content, overwriting part of that content
  2140. client.WriteAllLines(remoteFile, linesToWrite1);
  2141. using (var fs = client.OpenRead(remoteFile))
  2142. {
  2143. var actualBytes = new byte[fs.Length];
  2144. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2145. Assert.IsTrue(expectedBytes1.IsEqualTo(actualBytes));
  2146. }
  2147. #endregion Write less bytes than the current content, overwriting part of that content
  2148. #region Write more bytes than the current content, overwriting and appending to that content
  2149. client.WriteAllLines(remoteFile, linesToWrite2);
  2150. using (var fs = client.OpenRead(remoteFile))
  2151. {
  2152. var actualBytes = new byte[fs.Length];
  2153. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2154. Assert.IsTrue(expectedBytes2.IsEqualTo(actualBytes));
  2155. }
  2156. #endregion Write more bytes than the current content, overwriting and appending to that content
  2157. }
  2158. finally
  2159. {
  2160. if (client.Exists(remoteFile))
  2161. {
  2162. client.DeleteFile(remoteFile);
  2163. }
  2164. }
  2165. }
  2166. }
  2167. [TestMethod]
  2168. public void Sftp_WriteAllLines_Array_NoEncoding_FileDoesNotExist()
  2169. {
  2170. var encoding = new UTF8Encoding(false, true);
  2171. var linesToWrite = new[] { "\u0139isa", "&", "Sofie" };
  2172. var linesToWriteBytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite) + Environment.NewLine, encoding);
  2173. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2174. {
  2175. client.Connect();
  2176. var remoteFile = GenerateUniqueRemoteFileName();
  2177. if (client.Exists(remoteFile))
  2178. {
  2179. client.DeleteFile(remoteFile);
  2180. }
  2181. try
  2182. {
  2183. client.WriteAllLines(remoteFile, linesToWrite);
  2184. using (var fs = client.OpenRead(remoteFile))
  2185. {
  2186. var actualBytes = new byte[fs.Length];
  2187. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2188. Assert.IsTrue(linesToWriteBytes.IsEqualTo(actualBytes));
  2189. }
  2190. }
  2191. finally
  2192. {
  2193. if (client.Exists(remoteFile))
  2194. {
  2195. client.DeleteFile(remoteFile);
  2196. }
  2197. }
  2198. }
  2199. }
  2200. [TestMethod]
  2201. public void Sftp_WriteAllLines_Array_Encoding_DirectoryDoesNotExist()
  2202. {
  2203. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  2204. var encoding = GetRandomEncoding();
  2205. var linesToWrite = new[] { "Forever", "&", "\u0116ver" };
  2206. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2207. {
  2208. client.Connect();
  2209. if (client.Exists(remoteFile))
  2210. {
  2211. client.DeleteFile(remoteFile);
  2212. }
  2213. try
  2214. {
  2215. client.WriteAllLines(remoteFile, linesToWrite, encoding);
  2216. Assert.Fail();
  2217. }
  2218. catch (SftpPathNotFoundException ex)
  2219. {
  2220. Assert.IsNull(ex.InnerException);
  2221. Assert.AreEqual("No such file", ex.Message);
  2222. }
  2223. finally
  2224. {
  2225. if (client.Exists(remoteFile))
  2226. {
  2227. client.DeleteFile(remoteFile);
  2228. }
  2229. }
  2230. }
  2231. }
  2232. [TestMethod]
  2233. public void Sftp_WriteAllLines_Array_Encoding_ExistingFile()
  2234. {
  2235. const string initialContent = "\u0100ert & Ann Forever & Ever Lisa & Sofie";
  2236. var encoding = GetRandomEncoding();
  2237. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  2238. var linesToWrite1 = new[] { "Forever", "&", "\u0116ver" };
  2239. var linesToWrite1Bytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite1) + Environment.NewLine, encoding);
  2240. var expectedBytes1 = new ArrayBuilder<byte>().Add(linesToWrite1Bytes)
  2241. .Add(initialContentBytes, linesToWrite1Bytes.Length, initialContentBytes.Length - linesToWrite1Bytes.Length)
  2242. .Build();
  2243. var linesToWrite2 = new[] { "Forever", "&", "\u0116ver", "Gert & Ann", "Lisa + Sofie" };
  2244. var linesToWrite2Bytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite2) + Environment.NewLine, encoding);
  2245. var expectedBytes2 = linesToWrite2Bytes;
  2246. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2247. {
  2248. client.Connect();
  2249. var remoteFile = GenerateUniqueRemoteFileName();
  2250. if (client.Exists(remoteFile))
  2251. {
  2252. client.DeleteFile(remoteFile);
  2253. }
  2254. try
  2255. {
  2256. // create initial content
  2257. client.WriteAllText(remoteFile, initialContent, encoding);
  2258. #region Write less bytes than the current content, overwriting part of that content
  2259. client.WriteAllLines(remoteFile, linesToWrite1, encoding);
  2260. using (var fs = client.OpenRead(remoteFile))
  2261. {
  2262. var actualBytes = new byte[fs.Length];
  2263. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2264. Assert.IsTrue(expectedBytes1.IsEqualTo(actualBytes));
  2265. }
  2266. #endregion Write less bytes than the current content, overwriting part of that content
  2267. #region Write more bytes than the current content, overwriting and appending to that content
  2268. client.WriteAllLines(remoteFile, linesToWrite2, encoding);
  2269. using (var fs = client.OpenRead(remoteFile))
  2270. {
  2271. var actualBytes = new byte[fs.Length];
  2272. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2273. Assert.IsTrue(expectedBytes2.IsEqualTo(actualBytes));
  2274. }
  2275. #endregion Write more bytes than the current content, overwriting and appending to that content
  2276. }
  2277. finally
  2278. {
  2279. if (client.Exists(remoteFile))
  2280. {
  2281. client.DeleteFile(remoteFile);
  2282. }
  2283. }
  2284. }
  2285. }
  2286. [TestMethod]
  2287. public void Sftp_WriteAllLines_Array_Encoding_FileDoesNotExist()
  2288. {
  2289. var encoding = GetRandomEncoding();
  2290. var linesToWrite = new[] { "\u0139isa", "&", "Sofie" };
  2291. var linesToWriteBytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite) + Environment.NewLine, encoding);
  2292. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2293. {
  2294. client.Connect();
  2295. var remoteFile = GenerateUniqueRemoteFileName();
  2296. if (client.Exists(remoteFile))
  2297. {
  2298. client.DeleteFile(remoteFile);
  2299. }
  2300. try
  2301. {
  2302. client.WriteAllLines(remoteFile, linesToWrite, encoding);
  2303. using (var fs = client.OpenRead(remoteFile))
  2304. {
  2305. var actualBytes = new byte[fs.Length];
  2306. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2307. Assert.IsTrue(linesToWriteBytes.IsEqualTo(actualBytes));
  2308. }
  2309. }
  2310. finally
  2311. {
  2312. if (client.Exists(remoteFile))
  2313. {
  2314. client.DeleteFile(remoteFile);
  2315. }
  2316. }
  2317. }
  2318. }
  2319. [TestMethod]
  2320. public void Sftp_WriteAllText_NoEncoding_DirectoryDoesNotExist()
  2321. {
  2322. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  2323. const string initialContent = "\u0100ert & Ann Forever & \u0116ver Lisa & Sofie";
  2324. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2325. {
  2326. client.Connect();
  2327. if (client.Exists(remoteFile))
  2328. {
  2329. client.DeleteFile(remoteFile);
  2330. }
  2331. try
  2332. {
  2333. client.WriteAllText(remoteFile, initialContent);
  2334. Assert.Fail();
  2335. }
  2336. catch (SftpPathNotFoundException ex)
  2337. {
  2338. Assert.IsNull(ex.InnerException);
  2339. Assert.AreEqual("No such file", ex.Message);
  2340. }
  2341. finally
  2342. {
  2343. if (client.Exists(remoteFile))
  2344. {
  2345. client.DeleteFile(remoteFile);
  2346. }
  2347. }
  2348. }
  2349. }
  2350. [TestMethod]
  2351. public void Sftp_WriteAllText_NoEncoding_ExistingFile()
  2352. {
  2353. const string initialContent = "\u0100ert & Ann Forever & \u0116ver Lisa & Sofie";
  2354. const string newContent1 = "For\u0116ver & Ever";
  2355. var encoding = new UTF8Encoding(false, true);
  2356. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  2357. var newContent1Bytes = GetBytesWithPreamble(newContent1, encoding);
  2358. var expectedBytes1 = new ArrayBuilder<byte>().Add(newContent1Bytes)
  2359. .Add(initialContentBytes, newContent1Bytes.Length, initialContentBytes.Length - newContent1Bytes.Length)
  2360. .Build();
  2361. var newContent2 = "Sofie & Lisa For\u0116ver & Ever with \u0100ert & Ann";
  2362. var newContent2Bytes = GetBytesWithPreamble(newContent2, encoding);
  2363. var expectedBytes2 = newContent2Bytes;
  2364. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2365. {
  2366. client.Connect();
  2367. var remoteFile = GenerateUniqueRemoteFileName();
  2368. if (client.Exists(remoteFile))
  2369. {
  2370. client.DeleteFile(remoteFile);
  2371. }
  2372. try
  2373. {
  2374. client.WriteAllText(remoteFile, initialContent);
  2375. #region Write less bytes than the current content, overwriting part of that content
  2376. client.WriteAllText(remoteFile, newContent1);
  2377. using (var fs = client.OpenRead(remoteFile))
  2378. {
  2379. var actualBytes = new byte[fs.Length];
  2380. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2381. Assert.IsTrue(expectedBytes1.IsEqualTo(actualBytes));
  2382. }
  2383. #endregion Write less bytes than the current content, overwriting part of that content
  2384. #region Write more bytes than the current content, overwriting and appending to that content
  2385. client.WriteAllText(remoteFile, newContent2);
  2386. using (var fs = client.OpenRead(remoteFile))
  2387. {
  2388. var actualBytes = new byte[fs.Length];
  2389. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2390. Assert.IsTrue(expectedBytes2.IsEqualTo(actualBytes));
  2391. }
  2392. #endregion Write more bytes than the current content, overwriting and appending to that content
  2393. }
  2394. finally
  2395. {
  2396. if (client.Exists(remoteFile))
  2397. {
  2398. client.DeleteFile(remoteFile);
  2399. }
  2400. }
  2401. }
  2402. }
  2403. [TestMethod]
  2404. public void Sftp_WriteAllText_NoEncoding_FileDoesNotExist()
  2405. {
  2406. const string initialContent = "\u0100ert & Ann Forever & \u0116ver Lisa & Sofie";
  2407. var encoding = new UTF8Encoding(false, true);
  2408. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  2409. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2410. {
  2411. client.Connect();
  2412. var remoteFile = GenerateUniqueRemoteFileName();
  2413. if (client.Exists(remoteFile))
  2414. {
  2415. client.DeleteFile(remoteFile);
  2416. }
  2417. try
  2418. {
  2419. client.WriteAllText(remoteFile, initialContent);
  2420. using (var fs = client.OpenRead(remoteFile))
  2421. {
  2422. var actualBytes = new byte[fs.Length];
  2423. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2424. Assert.IsTrue(initialContentBytes.IsEqualTo(actualBytes));
  2425. }
  2426. }
  2427. finally
  2428. {
  2429. if (client.Exists(remoteFile))
  2430. {
  2431. client.DeleteFile(remoteFile);
  2432. }
  2433. }
  2434. }
  2435. }
  2436. [TestMethod]
  2437. public void Sftp_WriteAllText_Encoding_DirectoryDoesNotExist()
  2438. {
  2439. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  2440. var encoding = GetRandomEncoding();
  2441. const string content = "For\u0116ver & Ever";
  2442. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2443. {
  2444. client.Connect();
  2445. if (client.Exists(remoteFile))
  2446. {
  2447. client.DeleteFile(remoteFile);
  2448. }
  2449. try
  2450. {
  2451. client.WriteAllText(remoteFile, content, encoding);
  2452. Assert.Fail();
  2453. }
  2454. catch (SftpPathNotFoundException ex)
  2455. {
  2456. Assert.IsNull(ex.InnerException);
  2457. Assert.AreEqual("No such file", ex.Message);
  2458. }
  2459. finally
  2460. {
  2461. if (client.Exists(remoteFile))
  2462. {
  2463. client.DeleteFile(remoteFile);
  2464. }
  2465. }
  2466. }
  2467. }
  2468. [TestMethod]
  2469. public void Sftp_WriteAllText_Encoding_ExistingFile()
  2470. {
  2471. const string initialContent = "\u0100ert & Ann Forever & \u0116ver Lisa & Sofie";
  2472. const string newContent1 = "For\u0116ver & Ever";
  2473. const string newContent2 = "Sofie & Lisa For\u0116ver & Ever with \u0100ert & Ann";
  2474. var encoding = GetRandomEncoding();
  2475. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  2476. var newContent1Bytes = GetBytesWithPreamble(newContent1, encoding);
  2477. var expectedBytes1 = new ArrayBuilder<byte>().Add(newContent1Bytes)
  2478. .Add(initialContentBytes, newContent1Bytes.Length, initialContentBytes.Length - newContent1Bytes.Length)
  2479. .Build();
  2480. var newContent2Bytes = GetBytesWithPreamble(newContent2, encoding);
  2481. var expectedBytes2 = newContent2Bytes;
  2482. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2483. {
  2484. client.Connect();
  2485. var remoteFile = GenerateUniqueRemoteFileName();
  2486. if (client.Exists(remoteFile))
  2487. {
  2488. client.DeleteFile(remoteFile);
  2489. }
  2490. try
  2491. {
  2492. client.WriteAllText(remoteFile, initialContent, encoding);
  2493. #region Write less bytes than the current content, overwriting part of that content
  2494. client.WriteAllText(remoteFile, newContent1, encoding);
  2495. using (var fs = client.OpenRead(remoteFile))
  2496. {
  2497. var actualBytes = new byte[fs.Length];
  2498. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2499. Assert.IsTrue(expectedBytes1.IsEqualTo(actualBytes));
  2500. }
  2501. #endregion Write less bytes than the current content, overwriting part of that content
  2502. #region Write more bytes than the current content, overwriting and appending to that content
  2503. client.WriteAllText(remoteFile, newContent2, encoding);
  2504. using (var fs = client.OpenRead(remoteFile))
  2505. {
  2506. var actualBytes = new byte[fs.Length];
  2507. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2508. Assert.IsTrue(expectedBytes2.IsEqualTo(actualBytes));
  2509. }
  2510. #endregion Write more bytes than the current content, overwriting and appending to that content
  2511. }
  2512. finally
  2513. {
  2514. if (client.Exists(remoteFile))
  2515. {
  2516. client.DeleteFile(remoteFile);
  2517. }
  2518. }
  2519. }
  2520. }
  2521. [TestMethod]
  2522. public void Sftp_WriteAllText_Encoding_FileDoesNotExist()
  2523. {
  2524. const string initialContent = "\u0100ert & Ann Forever & \u0116ver Lisa & Sofie";
  2525. var encoding = GetRandomEncoding();
  2526. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  2527. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2528. {
  2529. client.Connect();
  2530. var remoteFile = GenerateUniqueRemoteFileName();
  2531. if (client.Exists(remoteFile))
  2532. {
  2533. client.DeleteFile(remoteFile);
  2534. }
  2535. try
  2536. {
  2537. client.WriteAllText(remoteFile, initialContent, encoding);
  2538. using (var fs = client.OpenRead(remoteFile))
  2539. {
  2540. var actualBytes = new byte[fs.Length];
  2541. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2542. Assert.IsTrue(initialContentBytes.IsEqualTo(actualBytes));
  2543. }
  2544. }
  2545. finally
  2546. {
  2547. if (client.Exists(remoteFile))
  2548. {
  2549. client.DeleteFile(remoteFile);
  2550. }
  2551. }
  2552. }
  2553. }
  2554. [TestMethod]
  2555. public void Sftp_BeginDownloadFile_FileDoesNotExist()
  2556. {
  2557. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2558. {
  2559. client.Connect();
  2560. var remoteFile = GenerateUniqueRemoteFileName();
  2561. if (client.Exists(remoteFile))
  2562. {
  2563. client.DeleteFile(remoteFile);
  2564. }
  2565. try
  2566. {
  2567. using (var ms = new MemoryStream())
  2568. {
  2569. var asyncResult = client.BeginDownloadFile(remoteFile, ms);
  2570. try
  2571. {
  2572. client.EndDownloadFile(asyncResult);
  2573. Assert.Fail();
  2574. }
  2575. catch (SftpPathNotFoundException ex)
  2576. {
  2577. Assert.IsNull(ex.InnerException);
  2578. Assert.AreEqual("No such file", ex.Message);
  2579. // ensure file was not created by us
  2580. Assert.IsFalse(client.Exists(remoteFile));
  2581. }
  2582. }
  2583. }
  2584. finally
  2585. {
  2586. if (client.Exists(remoteFile))
  2587. {
  2588. client.DeleteFile(remoteFile);
  2589. }
  2590. }
  2591. }
  2592. }
  2593. [TestMethod]
  2594. public void Sftp_BeginListDirectory_DirectoryDoesNotExist()
  2595. {
  2596. const string remoteDirectory = "/home/sshnet/test123";
  2597. using (var client = new SshClient(_connectionInfoFactory.Create()))
  2598. {
  2599. client.Connect();
  2600. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  2601. {
  2602. command.Execute();
  2603. }
  2604. }
  2605. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2606. {
  2607. client.Connect();
  2608. var asyncResult = client.BeginListDirectory(remoteDirectory, null, null);
  2609. try
  2610. {
  2611. client.EndListDirectory(asyncResult);
  2612. Assert.Fail();
  2613. }
  2614. catch (SftpPathNotFoundException ex)
  2615. {
  2616. Assert.IsNull(ex.InnerException);
  2617. Assert.AreEqual("No such file", ex.Message);
  2618. // ensure directory was not created by us
  2619. Assert.IsFalse(client.Exists(remoteDirectory));
  2620. }
  2621. }
  2622. }
  2623. [TestMethod]
  2624. public void Sftp_BeginUploadFile_InputAndPath_DirectoryDoesNotExist()
  2625. {
  2626. const int size = 50 * 1024 * 1024;
  2627. const string remoteDirectory = "/home/sshnet/test123";
  2628. const string remoteFile = remoteDirectory + "/test";
  2629. using (var client = new SshClient(_connectionInfoFactory.Create()))
  2630. {
  2631. client.Connect();
  2632. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  2633. {
  2634. command.Execute();
  2635. }
  2636. }
  2637. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2638. {
  2639. client.Connect();
  2640. var memoryStream = CreateMemoryStream(size);
  2641. memoryStream.Position = 0;
  2642. var asyncResult = client.BeginUploadFile(memoryStream, remoteFile);
  2643. try
  2644. {
  2645. client.EndUploadFile(asyncResult);
  2646. Assert.Fail();
  2647. }
  2648. catch (SftpPathNotFoundException)
  2649. {
  2650. }
  2651. }
  2652. }
  2653. [TestMethod]
  2654. public void Sftp_BeginUploadFile_InputAndPath_FileDoesNotExist()
  2655. {
  2656. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2657. {
  2658. client.Connect();
  2659. var remoteFile = GenerateUniqueRemoteFileName();
  2660. if (client.Exists(remoteFile))
  2661. {
  2662. client.DeleteFile(remoteFile);
  2663. }
  2664. try
  2665. {
  2666. var uploadMemoryStream = new MemoryStream();
  2667. var sw = new StreamWriter(uploadMemoryStream, Encoding.UTF8);
  2668. sw.Write("Gert & Ann");
  2669. sw.Flush();
  2670. uploadMemoryStream.Position = 0;
  2671. var asyncResult = client.BeginUploadFile(uploadMemoryStream, remoteFile);
  2672. client.EndUploadFile(asyncResult);
  2673. using (var downloadMemoryStream = new MemoryStream())
  2674. {
  2675. client.DownloadFile(remoteFile, downloadMemoryStream);
  2676. downloadMemoryStream.Position = 0;
  2677. using (var sr = new StreamReader(downloadMemoryStream, Encoding.UTF8))
  2678. {
  2679. var content = sr.ReadToEnd();
  2680. Assert.AreEqual("Gert & Ann", content);
  2681. }
  2682. }
  2683. }
  2684. finally
  2685. {
  2686. if (client.Exists(remoteFile))
  2687. {
  2688. client.DeleteFile(remoteFile);
  2689. }
  2690. }
  2691. }
  2692. }
  2693. [TestMethod]
  2694. public void Sftp_BeginUploadFile_InputAndPath_ExistingFile()
  2695. {
  2696. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2697. {
  2698. client.Connect();
  2699. var remoteFile = GenerateUniqueRemoteFileName();
  2700. if (client.Exists(remoteFile))
  2701. {
  2702. client.DeleteFile(remoteFile);
  2703. }
  2704. try
  2705. {
  2706. client.WriteAllText(remoteFile, "Gert & Ann & Lisa");
  2707. var uploadMemoryStream = new MemoryStream();
  2708. var sw = new StreamWriter(uploadMemoryStream, Encoding.UTF8);
  2709. sw.Write("Ann & Gert");
  2710. sw.Flush();
  2711. uploadMemoryStream.Position = 0;
  2712. var asyncResult = client.BeginUploadFile(uploadMemoryStream, remoteFile);
  2713. client.EndUploadFile(asyncResult);
  2714. using (var downloadMemoryStream = new MemoryStream())
  2715. {
  2716. client.DownloadFile(remoteFile, downloadMemoryStream);
  2717. downloadMemoryStream.Position = 0;
  2718. using (var sr = new StreamReader(downloadMemoryStream, Encoding.UTF8))
  2719. {
  2720. var content = sr.ReadToEnd();
  2721. Assert.AreEqual("Ann & Gert", content);
  2722. }
  2723. }
  2724. }
  2725. finally
  2726. {
  2727. if (client.Exists(remoteFile))
  2728. {
  2729. client.DeleteFile(remoteFile);
  2730. }
  2731. }
  2732. }
  2733. }
  2734. [TestMethod]
  2735. public void Sftp_BeginUploadFile_InputAndPathAndCanOverride_CanOverrideIsFalse_DirectoryDoesNotExist()
  2736. {
  2737. const int size = 50 * 1024 * 1024;
  2738. const string remoteDirectory = "/home/sshnet/test123";
  2739. const string remoteFile = remoteDirectory + "/test";
  2740. using (var client = new SshClient(_connectionInfoFactory.Create()))
  2741. {
  2742. client.Connect();
  2743. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  2744. {
  2745. command.Execute();
  2746. }
  2747. }
  2748. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2749. {
  2750. client.Connect();
  2751. var memoryStream = CreateMemoryStream(size);
  2752. memoryStream.Position = 0;
  2753. var asyncResult = client.BeginUploadFile(memoryStream, remoteFile, false, null, null);
  2754. try
  2755. {
  2756. client.EndUploadFile(asyncResult);
  2757. Assert.Fail();
  2758. }
  2759. catch (SftpPathNotFoundException)
  2760. {
  2761. }
  2762. }
  2763. }
  2764. [TestMethod]
  2765. public void Sftp_BeginUploadFile_InputAndPathAndCanOverride_CanOverrideIsFalse_FileDoesNotExist()
  2766. {
  2767. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2768. {
  2769. client.Connect();
  2770. var remoteFile = GenerateUniqueRemoteFileName();
  2771. if (client.Exists(remoteFile))
  2772. {
  2773. client.DeleteFile(remoteFile);
  2774. }
  2775. try
  2776. {
  2777. using (var uploadMemoryStream = new MemoryStream())
  2778. using (var sw = new StreamWriter(uploadMemoryStream, Encoding.UTF8))
  2779. {
  2780. sw.Write("Gert & Ann");
  2781. sw.Flush();
  2782. uploadMemoryStream.Position = 0;
  2783. var asyncResult = client.BeginUploadFile(uploadMemoryStream, remoteFile, false, null, null);
  2784. client.EndUploadFile(asyncResult);
  2785. }
  2786. using (var downloadMemoryStream = new MemoryStream())
  2787. {
  2788. client.DownloadFile(remoteFile, downloadMemoryStream);
  2789. downloadMemoryStream.Position = 0;
  2790. using (var sr = new StreamReader(downloadMemoryStream, Encoding.UTF8))
  2791. {
  2792. var content = sr.ReadToEnd();
  2793. Assert.AreEqual("Gert & Ann", content);
  2794. }
  2795. }
  2796. }
  2797. finally
  2798. {
  2799. if (client.Exists(remoteFile))
  2800. {
  2801. client.DeleteFile(remoteFile);
  2802. }
  2803. }
  2804. }
  2805. }
  2806. [TestMethod]
  2807. public void Sftp_BeginUploadFile_InputAndPathAndCanOverride_CanOverrideIsFalse_ExistingFile()
  2808. {
  2809. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2810. {
  2811. client.Connect();
  2812. var remoteFile = GenerateUniqueRemoteFileName();
  2813. if (client.Exists(remoteFile))
  2814. {
  2815. client.DeleteFile(remoteFile);
  2816. }
  2817. try
  2818. {
  2819. client.WriteAllText(remoteFile, "Gert & Ann & Lisa");
  2820. var uploadMemoryStream = new MemoryStream();
  2821. var sw = new StreamWriter(uploadMemoryStream, Encoding.UTF8);
  2822. sw.Write("Ann & Gert");
  2823. sw.Flush();
  2824. uploadMemoryStream.Position = 0;
  2825. var asyncResult = client.BeginUploadFile(uploadMemoryStream, remoteFile, false, null, null);
  2826. try
  2827. {
  2828. client.EndUploadFile(asyncResult);
  2829. Assert.Fail();
  2830. }
  2831. catch (SshException ex)
  2832. {
  2833. Assert.AreEqual(typeof(SshException), ex.GetType());
  2834. Assert.IsNull(ex.InnerException);
  2835. Assert.AreEqual("Failure", ex.Message);
  2836. }
  2837. }
  2838. finally
  2839. {
  2840. if (client.Exists(remoteFile))
  2841. {
  2842. client.DeleteFile(remoteFile);
  2843. }
  2844. }
  2845. }
  2846. }
  2847. [TestMethod]
  2848. public void Sftp_BeginUploadFile_InputAndPathAndCanOverride_CanOverrideIsTrue_DirectoryDoesNotExist()
  2849. {
  2850. const int size = 50 * 1024 * 1024;
  2851. const string remoteDirectory = "/home/sshnet/test123";
  2852. const string remoteFile = remoteDirectory + "/test";
  2853. using (var client = new SshClient(_connectionInfoFactory.Create()))
  2854. {
  2855. client.Connect();
  2856. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  2857. {
  2858. command.Execute();
  2859. }
  2860. }
  2861. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2862. {
  2863. client.Connect();
  2864. var memoryStream = CreateMemoryStream(size);
  2865. memoryStream.Position = 0;
  2866. var asyncResult = client.BeginUploadFile(memoryStream, remoteFile, true, null, null);
  2867. try
  2868. {
  2869. client.EndUploadFile(asyncResult);
  2870. Assert.Fail();
  2871. }
  2872. catch (SftpPathNotFoundException)
  2873. {
  2874. }
  2875. }
  2876. }
  2877. [TestMethod]
  2878. public void Sftp_BeginUploadFile_InputAndPathAndCanOverride_CanOverrideIsTrue_FileDoesNotExist()
  2879. {
  2880. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2881. {
  2882. client.Connect();
  2883. var remoteFile = GenerateUniqueRemoteFileName();
  2884. if (client.Exists(remoteFile))
  2885. {
  2886. client.DeleteFile(remoteFile);
  2887. }
  2888. try
  2889. {
  2890. using (var uploadMemoryStream = new MemoryStream())
  2891. using (var sw = new StreamWriter(uploadMemoryStream, Encoding.UTF8))
  2892. {
  2893. sw.Write("Gert & Ann");
  2894. sw.Flush();
  2895. uploadMemoryStream.Position = 0;
  2896. var asyncResult = client.BeginUploadFile(uploadMemoryStream, remoteFile, true, null, null);
  2897. client.EndUploadFile(asyncResult);
  2898. }
  2899. using (var downloadMemoryStream = new MemoryStream())
  2900. {
  2901. client.DownloadFile(remoteFile, downloadMemoryStream);
  2902. downloadMemoryStream.Position = 0;
  2903. using (var sr = new StreamReader(downloadMemoryStream, Encoding.UTF8))
  2904. {
  2905. var content = sr.ReadToEnd();
  2906. Assert.AreEqual("Gert & Ann", content);
  2907. }
  2908. }
  2909. }
  2910. finally
  2911. {
  2912. if (client.Exists(remoteFile))
  2913. {
  2914. client.DeleteFile(remoteFile);
  2915. }
  2916. }
  2917. }
  2918. }
  2919. [TestMethod]
  2920. public void Sftp_BeginUploadFile_InputAndPathAndCanOverride_CanOverrideIsTrue_ExistingFile()
  2921. {
  2922. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2923. {
  2924. client.Connect();
  2925. var remoteFile = GenerateUniqueRemoteFileName();
  2926. if (client.Exists(remoteFile))
  2927. {
  2928. client.DeleteFile(remoteFile);
  2929. }
  2930. try
  2931. {
  2932. client.WriteAllText(remoteFile, "Gert & Ann & Lisa");
  2933. using (var uploadMemoryStream = new MemoryStream())
  2934. using (var sw = new StreamWriter(uploadMemoryStream, Encoding.UTF8))
  2935. {
  2936. sw.Write("Ann & Gert");
  2937. sw.Flush();
  2938. uploadMemoryStream.Position = 0;
  2939. var asyncResult = client.BeginUploadFile(uploadMemoryStream, remoteFile, true, null, null);
  2940. client.EndUploadFile(asyncResult);
  2941. }
  2942. using (var downloadMemoryStream = new MemoryStream())
  2943. {
  2944. client.DownloadFile(remoteFile, downloadMemoryStream);
  2945. downloadMemoryStream.Position = 0;
  2946. using (var sr = new StreamReader(downloadMemoryStream, Encoding.UTF8))
  2947. {
  2948. var content = sr.ReadToEnd();
  2949. Assert.AreEqual("Ann & Gert", content);
  2950. }
  2951. }
  2952. }
  2953. finally
  2954. {
  2955. if (client.Exists(remoteFile))
  2956. {
  2957. client.DeleteFile(remoteFile);
  2958. }
  2959. }
  2960. }
  2961. }
  2962. [TestMethod]
  2963. public void Sftp_UploadAndDownloadBigFile()
  2964. {
  2965. const int size = 50 * 1024 * 1024;
  2966. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2967. {
  2968. client.Connect();
  2969. var remoteFile = GenerateUniqueRemoteFileName();
  2970. if (client.Exists(remoteFile))
  2971. {
  2972. client.Delete(remoteFile);
  2973. }
  2974. try
  2975. {
  2976. var memoryStream = CreateMemoryStream(size);
  2977. memoryStream.Position = 0;
  2978. client.UploadFile(memoryStream, remoteFile);
  2979. var stopwatch = new Stopwatch();
  2980. stopwatch.Start();
  2981. // check uploaded file
  2982. memoryStream = new MemoryStream();
  2983. client.DownloadFile(remoteFile, memoryStream);
  2984. Assert.AreEqual(size, memoryStream.Length);
  2985. stopwatch.Stop();
  2986. Console.WriteLine(@"Elapsed: {0} ms", stopwatch.ElapsedMilliseconds);
  2987. Console.WriteLine(@"Transfer speed: {0:N2} KB/s",
  2988. CalculateTransferSpeed(memoryStream.Length, stopwatch.ElapsedMilliseconds));
  2989. }
  2990. finally
  2991. {
  2992. if (client.Exists(remoteFile))
  2993. {
  2994. client.Delete(remoteFile);
  2995. }
  2996. }
  2997. }
  2998. }
  2999. /// <summary>
  3000. /// Issue 1672
  3001. /// </summary>
  3002. [TestMethod]
  3003. public void Sftp_CurrentWorkingDirectory()
  3004. {
  3005. const string homeDirectory = "/home/sshnet";
  3006. const string otherDirectory = homeDirectory + "/dir";
  3007. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3008. {
  3009. client.Connect();
  3010. if (client.Exists(otherDirectory))
  3011. {
  3012. client.DeleteDirectory(otherDirectory);
  3013. }
  3014. try
  3015. {
  3016. client.CreateDirectory(otherDirectory);
  3017. client.ChangeDirectory(otherDirectory);
  3018. using (var s = CreateStreamWithContent("A"))
  3019. {
  3020. client.UploadFile(s, "a.txt");
  3021. }
  3022. using (var s = new MemoryStream())
  3023. {
  3024. client.DownloadFile("a.txt", s);
  3025. s.Position = 0;
  3026. var content = Encoding.ASCII.GetString(s.ToArray());
  3027. Assert.AreEqual("A", content);
  3028. }
  3029. Assert.IsTrue(client.Exists(otherDirectory + "/a.txt"));
  3030. client.DeleteFile("a.txt");
  3031. Assert.IsFalse(client.Exists(otherDirectory + "/a.txt"));
  3032. client.DeleteDirectory(".");
  3033. Assert.IsFalse(client.Exists(otherDirectory));
  3034. }
  3035. finally
  3036. {
  3037. if (client.Exists(otherDirectory))
  3038. {
  3039. client.DeleteDirectory(otherDirectory);
  3040. }
  3041. }
  3042. }
  3043. }
  3044. [TestMethod]
  3045. public void Sftp_Exists()
  3046. {
  3047. const string remoteHome = "/home/sshnet";
  3048. #region Setup
  3049. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3050. {
  3051. client.Connect();
  3052. #region Clean-up
  3053. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/DoesNotExist"}"))
  3054. {
  3055. command.Execute();
  3056. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3057. }
  3058. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/symlink.to.directory.exists"}"))
  3059. {
  3060. command.Execute();
  3061. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3062. }
  3063. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/directory.exists"}")
  3064. )
  3065. {
  3066. command.Execute();
  3067. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3068. }
  3069. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/symlink.to.file.exists"}"))
  3070. {
  3071. command.Execute();
  3072. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3073. }
  3074. using (var command = client.CreateCommand($"rm -f {remoteHome + "/file.exists"}"))
  3075. {
  3076. command.Execute();
  3077. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3078. }
  3079. #endregion Clean-up
  3080. #region Setup
  3081. using (var command = client.CreateCommand($"touch {remoteHome + "/file.exists"}"))
  3082. {
  3083. command.Execute();
  3084. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3085. }
  3086. using (var command = client.CreateCommand($"mkdir {remoteHome + "/directory.exists"}"))
  3087. {
  3088. command.Execute();
  3089. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3090. }
  3091. using (var command = client.CreateCommand($"ln -s {remoteHome + "/file.exists"} {remoteHome + "/symlink.to.file.exists"}"))
  3092. {
  3093. command.Execute();
  3094. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3095. }
  3096. using (var command = client.CreateCommand($"ln -s {remoteHome + "/directory.exists"} {remoteHome + "/symlink.to.directory.exists"}"))
  3097. {
  3098. command.Execute();
  3099. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3100. }
  3101. #endregion Setup
  3102. }
  3103. #endregion Setup
  3104. #region Assert
  3105. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3106. {
  3107. client.Connect();
  3108. Assert.IsFalse(client.Exists(remoteHome + "/DoesNotExist"));
  3109. Assert.IsTrue(client.Exists(remoteHome + "/file.exists"));
  3110. Assert.IsTrue(client.Exists(remoteHome + "/symlink.to.file.exists"));
  3111. Assert.IsTrue(client.Exists(remoteHome + "/directory.exists"));
  3112. Assert.IsTrue(client.Exists(remoteHome + "/symlink.to.directory.exists"));
  3113. }
  3114. #endregion Assert
  3115. #region Teardown
  3116. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3117. {
  3118. client.Connect();
  3119. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/DoesNotExist"}"))
  3120. {
  3121. command.Execute();
  3122. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3123. }
  3124. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/symlink.to.directory.exists"}"))
  3125. {
  3126. command.Execute();
  3127. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3128. }
  3129. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/directory.exists"}"))
  3130. {
  3131. command.Execute();
  3132. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3133. }
  3134. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/symlink.to.file.exists"}"))
  3135. {
  3136. command.Execute();
  3137. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3138. }
  3139. using (var command = client.CreateCommand($"rm -f {remoteHome + "/file.exists"}"))
  3140. {
  3141. command.Execute();
  3142. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3143. }
  3144. }
  3145. #endregion Teardown
  3146. }
  3147. [TestMethod]
  3148. public void Sftp_ListDirectory()
  3149. {
  3150. const string remoteDirectory = "/home/sshnet/test123";
  3151. try
  3152. {
  3153. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3154. {
  3155. client.Connect();
  3156. client.RunCommand($@"rm -Rf ""{remoteDirectory}""");
  3157. client.RunCommand($@"mkdir -p ""{remoteDirectory}""");
  3158. client.RunCommand($@"mkdir -p ""{remoteDirectory}/sub""");
  3159. client.RunCommand($@"touch ""{remoteDirectory}/file1""");
  3160. client.RunCommand($@"touch ""{remoteDirectory}/file2""");
  3161. }
  3162. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3163. {
  3164. client.Connect();
  3165. client.ChangeDirectory(remoteDirectory);
  3166. var directoryContent = client.ListDirectory(".").OrderBy(p => p.Name).ToList();
  3167. Assert.AreEqual(5, directoryContent.Count);
  3168. Assert.AreEqual(".", directoryContent[0].Name);
  3169. Assert.AreEqual($"{remoteDirectory}/.", directoryContent[0].FullName);
  3170. Assert.IsTrue(directoryContent[0].IsDirectory);
  3171. Assert.AreEqual("..", directoryContent[1].Name);
  3172. Assert.AreEqual($"{remoteDirectory}/..", directoryContent[1].FullName);
  3173. Assert.IsTrue(directoryContent[1].IsDirectory);
  3174. Assert.AreEqual("file1", directoryContent[2].Name);
  3175. Assert.AreEqual($"{remoteDirectory}/file1", directoryContent[2].FullName);
  3176. Assert.IsFalse(directoryContent[2].IsDirectory);
  3177. Assert.AreEqual("file2", directoryContent[3].Name);
  3178. Assert.AreEqual($"{remoteDirectory}/file2", directoryContent[3].FullName);
  3179. Assert.IsFalse(directoryContent[3].IsDirectory);
  3180. Assert.AreEqual("sub", directoryContent[4].Name);
  3181. Assert.AreEqual($"{remoteDirectory}/sub", directoryContent[4].FullName);
  3182. Assert.IsTrue(directoryContent[4].IsDirectory);
  3183. }
  3184. }
  3185. finally
  3186. {
  3187. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3188. {
  3189. client.Connect();
  3190. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  3191. {
  3192. command.Execute();
  3193. }
  3194. }
  3195. }
  3196. }
  3197. [TestMethod]
  3198. public void Sftp_ChangeDirectory_DirectoryDoesNotExist()
  3199. {
  3200. const string remoteDirectory = "/home/sshnet/test123";
  3201. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3202. {
  3203. client.Connect();
  3204. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  3205. {
  3206. command.Execute();
  3207. }
  3208. }
  3209. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3210. {
  3211. client.Connect();
  3212. try
  3213. {
  3214. client.ChangeDirectory(remoteDirectory);
  3215. Assert.Fail();
  3216. }
  3217. catch (SftpPathNotFoundException)
  3218. {
  3219. }
  3220. }
  3221. }
  3222. [TestMethod]
  3223. public void Sftp_ChangeDirectory_DirectoryExists()
  3224. {
  3225. const string remoteDirectory = "/home/sshnet/test123";
  3226. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3227. {
  3228. client.Connect();
  3229. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  3230. {
  3231. command.Execute();
  3232. }
  3233. using (var command = client.CreateCommand("mkdir -p " + _remotePathTransformation.Transform(remoteDirectory)))
  3234. {
  3235. command.Execute();
  3236. }
  3237. }
  3238. try
  3239. {
  3240. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3241. {
  3242. client.Connect();
  3243. client.ChangeDirectory(remoteDirectory);
  3244. Assert.AreEqual(remoteDirectory, client.WorkingDirectory);
  3245. using (var uploadStream = CreateMemoryStream(100))
  3246. {
  3247. uploadStream.Position = 0;
  3248. client.UploadFile(uploadStream, "gert.txt");
  3249. uploadStream.Position = 0;
  3250. using (var downloadStream = client.OpenRead(remoteDirectory + "/gert.txt"))
  3251. {
  3252. Assert.AreEqual(CreateHash(uploadStream), CreateHash(downloadStream));
  3253. }
  3254. }
  3255. }
  3256. }
  3257. finally
  3258. {
  3259. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3260. {
  3261. client.Connect();
  3262. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  3263. {
  3264. command.Execute();
  3265. }
  3266. }
  3267. }
  3268. }
  3269. [TestMethod]
  3270. public void Sftp_DownloadFile_MemoryStream()
  3271. {
  3272. const int fileSize = 500 * 1024;
  3273. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3274. {
  3275. client.Connect();
  3276. var remoteFile = GenerateUniqueRemoteFileName();
  3277. SftpCreateRemoteFile(client, remoteFile, fileSize);
  3278. try
  3279. {
  3280. using (var memoryStream = new MemoryStream())
  3281. {
  3282. var stopwatch = new Stopwatch();
  3283. stopwatch.Start();
  3284. client.DownloadFile(remoteFile, memoryStream);
  3285. stopwatch.Stop();
  3286. var transferSpeed = CalculateTransferSpeed(memoryStream.Length, stopwatch.ElapsedMilliseconds);
  3287. Console.WriteLine(@"Elapsed: {0} ms", stopwatch.ElapsedMilliseconds);
  3288. Console.WriteLine(@"Transfer speed: {0:N2} KB/s", transferSpeed);
  3289. Assert.AreEqual(fileSize, memoryStream.Length);
  3290. }
  3291. }
  3292. finally
  3293. {
  3294. if (client.Exists(remoteFile))
  3295. {
  3296. client.DeleteFile(remoteFile);
  3297. }
  3298. }
  3299. }
  3300. }
  3301. [TestMethod]
  3302. public void Sftp_SubsystemExecution_Failed()
  3303. {
  3304. var remoteSshdConfig = new RemoteSshd(_adminConnectionInfoFactory).OpenConfig();
  3305. // Disable SFTP subsystem
  3306. remoteSshdConfig.ClearSubsystems()
  3307. .Update()
  3308. .Restart();
  3309. var remoteSshdReconfiguredToDefaultState = false;
  3310. try
  3311. {
  3312. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3313. {
  3314. try
  3315. {
  3316. client.Connect();
  3317. Assert.Fail("Establishing SFTP connection should have failed.");
  3318. }
  3319. catch (SshException ex)
  3320. {
  3321. Assert.IsNull(ex.InnerException);
  3322. Assert.AreEqual("Subsystem 'sftp' could not be executed.", ex.Message);
  3323. }
  3324. // Re-enable SFTP subsystem
  3325. remoteSshdConfig.Reset();
  3326. remoteSshdReconfiguredToDefaultState = true;
  3327. // ensure we can reconnect the same SftpClient instance
  3328. client.Connect();
  3329. // ensure SFTP session is correctly established
  3330. Assert.IsTrue(client.Exists("."));
  3331. }
  3332. }
  3333. finally
  3334. {
  3335. if (!remoteSshdReconfiguredToDefaultState)
  3336. {
  3337. remoteSshdConfig.Reset();
  3338. }
  3339. }
  3340. }
  3341. [TestMethod]
  3342. public void Sftp_SftpFileStream_ReadAndWrite()
  3343. {
  3344. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3345. {
  3346. client.Connect();
  3347. var remoteFile = GenerateUniqueRemoteFileName();
  3348. if (client.Exists(remoteFile))
  3349. {
  3350. client.DeleteFile(remoteFile);
  3351. }
  3352. try
  3353. {
  3354. using (var s = client.Open(remoteFile, FileMode.CreateNew, FileAccess.Write))
  3355. {
  3356. s.Write(new byte[] { 5, 4, 3, 2, 1 }, 1, 3);
  3357. }
  3358. // switch from read to write mode
  3359. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.ReadWrite))
  3360. {
  3361. Assert.AreEqual(4, s.ReadByte());
  3362. Assert.AreEqual(3, s.ReadByte());
  3363. Assert.AreEqual(2, s.Position);
  3364. s.WriteByte(7);
  3365. s.Write(new byte[] { 8, 9, 10, 11, 12 }, 1, 3);
  3366. Assert.AreEqual(6, s.Position);
  3367. }
  3368. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.Read))
  3369. {
  3370. Assert.AreEqual(6, s.Length);
  3371. var buffer = new byte[s.Length];
  3372. Assert.AreEqual(6, s.Read(buffer, offset: 0, buffer.Length));
  3373. CollectionAssert.AreEqual(new byte[] { 4, 3, 7, 9, 10, 11 }, buffer);
  3374. // Ensure we've reached end of the stream
  3375. Assert.AreEqual(-1, s.ReadByte());
  3376. }
  3377. // switch from read to write mode, and back to read mode and finally
  3378. // append a byte
  3379. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.ReadWrite))
  3380. {
  3381. Assert.AreEqual(4, s.ReadByte());
  3382. Assert.AreEqual(3, s.ReadByte());
  3383. Assert.AreEqual(7, s.ReadByte());
  3384. s.Write(new byte[] { 0, 1, 6, 4 }, 1, 2);
  3385. Assert.AreEqual(11, s.ReadByte());
  3386. // Ensure we've reached end of the stream
  3387. Assert.AreEqual(-1, s.ReadByte());
  3388. s.WriteByte(12);
  3389. }
  3390. // switch from write to read mode, and back to write mode
  3391. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.ReadWrite))
  3392. {
  3393. s.WriteByte(5);
  3394. Assert.AreEqual(3, s.ReadByte());
  3395. s.WriteByte(13);
  3396. Assert.AreEqual(3, s.Position);
  3397. }
  3398. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.Read))
  3399. {
  3400. Assert.AreEqual(7, s.Length);
  3401. var buffer = new byte[s.Length];
  3402. Assert.AreEqual(7, s.Read(buffer, offset: 0, buffer.Length));
  3403. CollectionAssert.AreEqual(new byte[] { 5, 3, 13, 1, 6, 11, 12 }, buffer);
  3404. // Ensure we've reached end of the stream
  3405. Assert.AreEqual(-1, s.ReadByte());
  3406. }
  3407. }
  3408. finally
  3409. {
  3410. if (client.Exists(remoteFile))
  3411. {
  3412. client.DeleteFile(remoteFile);
  3413. }
  3414. }
  3415. }
  3416. }
  3417. [TestMethod]
  3418. public void Sftp_SftpFileStream_SetLength_ReduceLength()
  3419. {
  3420. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3421. {
  3422. client.Connect();
  3423. var remoteFile = GenerateUniqueRemoteFileName();
  3424. if (client.Exists(remoteFile))
  3425. {
  3426. client.DeleteFile(remoteFile);
  3427. }
  3428. try
  3429. {
  3430. using (var s = client.Open(remoteFile, FileMode.CreateNew, FileAccess.Write))
  3431. {
  3432. s.Write(new byte[] { 5, 4, 3, 2, 1 }, 1, 3);
  3433. }
  3434. // reduce length while in write mode, with data in write buffer, and before
  3435. // current position
  3436. using (var s = client.Open(remoteFile, FileMode.Append, FileAccess.Write))
  3437. {
  3438. s.Position = 3;
  3439. s.Write(new byte[] { 6, 7, 8, 9 }, offset: 0, count: 4);
  3440. Assert.AreEqual(7, s.Position);
  3441. // verify buffer has not yet been flushed
  3442. using (var fs = client.Open(remoteFile, FileMode.Open, FileAccess.Read))
  3443. {
  3444. Assert.AreEqual(4, fs.ReadByte());
  3445. Assert.AreEqual(3, fs.ReadByte());
  3446. Assert.AreEqual(2, fs.ReadByte());
  3447. // Ensure we've reached end of the stream
  3448. Assert.AreEqual(-1, fs.ReadByte());
  3449. }
  3450. s.SetLength(5);
  3451. Assert.AreEqual(5, s.Position);
  3452. // verify that buffer was flushed and size has been modified
  3453. using (var fs = client.Open(remoteFile, FileMode.Open, FileAccess.Read))
  3454. {
  3455. Assert.AreEqual(4, fs.ReadByte());
  3456. Assert.AreEqual(3, fs.ReadByte());
  3457. Assert.AreEqual(2, fs.ReadByte());
  3458. Assert.AreEqual(6, fs.ReadByte());
  3459. Assert.AreEqual(7, fs.ReadByte());
  3460. // Ensure we've reached end of the stream
  3461. Assert.AreEqual(-1, fs.ReadByte());
  3462. }
  3463. s.WriteByte(1);
  3464. }
  3465. // verify that last byte was correctly written to the file
  3466. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.Read))
  3467. {
  3468. Assert.AreEqual(6, s.Length);
  3469. var buffer = new byte[s.Length + 2];
  3470. Assert.AreEqual(6, s.Read(buffer, offset: 0, buffer.Length));
  3471. CollectionAssert.AreEqual(new byte[] { 4, 3, 2, 6, 7, 1, 0, 0 }, buffer);
  3472. // Ensure we've reached end of the stream
  3473. Assert.AreEqual(-1, s.ReadByte());
  3474. }
  3475. // reduce length while in read mode, but beyond current position
  3476. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.ReadWrite))
  3477. {
  3478. var buffer = new byte[1];
  3479. Assert.AreEqual(1, s.Read(buffer, offset: 0, buffer.Length));
  3480. CollectionAssert.AreEqual(new byte[] { 4 }, buffer);
  3481. s.SetLength(3);
  3482. using (var w = client.Open(remoteFile, FileMode.Open, FileAccess.Write))
  3483. {
  3484. w.Write(new byte[] { 8, 1, 6, 2 }, offset: 0, count: 4);
  3485. }
  3486. // verify that position was not changed
  3487. Assert.AreEqual(1, s.Position);
  3488. // verify that read buffer was cleared
  3489. Assert.AreEqual(1, s.ReadByte());
  3490. Assert.AreEqual(6, s.ReadByte());
  3491. Assert.AreEqual(2, s.ReadByte());
  3492. // Ensure we've reached end of the stream
  3493. Assert.AreEqual(-1, s.ReadByte());
  3494. Assert.AreEqual(4, s.Length);
  3495. }
  3496. // reduce length while in read mode, but before current position
  3497. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.ReadWrite))
  3498. {
  3499. var buffer = new byte[4];
  3500. Assert.AreEqual(4, s.Read(buffer, offset: 0, buffer.Length));
  3501. CollectionAssert.AreEqual(new byte[] { 8, 1, 6, 2 }, buffer);
  3502. Assert.AreEqual(4, s.Position);
  3503. s.SetLength(3);
  3504. // verify that position was moved to last byte
  3505. Assert.AreEqual(3, s.Position);
  3506. using (var w = client.Open(remoteFile, FileMode.Open, FileAccess.Read))
  3507. {
  3508. Assert.AreEqual(3, w.Length);
  3509. Assert.AreEqual(8, w.ReadByte());
  3510. Assert.AreEqual(1, w.ReadByte());
  3511. Assert.AreEqual(6, w.ReadByte());
  3512. // Ensure we've reached end of the stream
  3513. Assert.AreEqual(-1, w.ReadByte());
  3514. }
  3515. // Ensure we've reached end of the stream
  3516. Assert.AreEqual(-1, s.ReadByte());
  3517. }
  3518. }
  3519. finally
  3520. {
  3521. if (client.Exists(remoteFile))
  3522. {
  3523. client.DeleteFile(remoteFile);
  3524. }
  3525. }
  3526. }
  3527. }
  3528. [TestMethod]
  3529. public void Sftp_SftpFileStream_Seek_BeyondEndOfFile_SeekOriginBegin()
  3530. {
  3531. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3532. {
  3533. client.BufferSize = 500;
  3534. client.Connect();
  3535. var remoteFile = GenerateUniqueRemoteFileName();
  3536. if (client.Exists(remoteFile))
  3537. {
  3538. client.DeleteFile(remoteFile);
  3539. }
  3540. try
  3541. {
  3542. // create single-byte file
  3543. using (var fs = client.OpenWrite(remoteFile))
  3544. {
  3545. fs.WriteByte(0x04);
  3546. }
  3547. // seek beyond EOF but not beyond buffer size
  3548. // do not write anything
  3549. using (var fs = client.OpenWrite(remoteFile))
  3550. {
  3551. var newPosition = fs.Seek(offset: 3L, SeekOrigin.Begin);
  3552. Assert.AreEqual(3, newPosition);
  3553. Assert.AreEqual(3, fs.Position);
  3554. }
  3555. using (var fs = client.OpenRead(remoteFile))
  3556. {
  3557. Assert.AreEqual(1, fs.Length);
  3558. Assert.AreEqual(0x04, fs.ReadByte());
  3559. // Ensure we've reached end of the stream
  3560. Assert.AreEqual(-1, fs.ReadByte());
  3561. }
  3562. client.DeleteFile(remoteFile);
  3563. // create single-byte file
  3564. using (var fs = client.OpenWrite(remoteFile))
  3565. {
  3566. fs.WriteByte(0x04);
  3567. }
  3568. // seek beyond EOF and beyond buffer size
  3569. // do not write anything
  3570. using (var fs = client.OpenWrite(remoteFile))
  3571. {
  3572. var newPosition = fs.Seek(offset: 700L, SeekOrigin.Begin);
  3573. Assert.AreEqual(700, newPosition);
  3574. Assert.AreEqual(700, fs.Position);
  3575. }
  3576. using (var fs = client.OpenRead(remoteFile))
  3577. {
  3578. Assert.AreEqual(1, fs.Length);
  3579. Assert.AreEqual(0x04, fs.ReadByte());
  3580. // Ensure we've reached end of the stream
  3581. Assert.AreEqual(-1, fs.ReadByte());
  3582. }
  3583. client.DeleteFile(remoteFile);
  3584. // create single-byte file
  3585. using (var fs = client.OpenWrite(remoteFile))
  3586. {
  3587. fs.WriteByte(0x04);
  3588. }
  3589. // seek beyond EOF but not beyond buffer size
  3590. // write less bytes than buffer size
  3591. var seekOffset = 3L;
  3592. // buffer holding the data that we'll write to the file
  3593. var writeBuffer = GenerateRandom(size: 7);
  3594. using (var fs = client.OpenWrite(remoteFile))
  3595. {
  3596. var newPosition = fs.Seek(seekOffset, SeekOrigin.Begin);
  3597. Assert.AreEqual(seekOffset, newPosition);
  3598. Assert.AreEqual(seekOffset, fs.Position);
  3599. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3600. }
  3601. using (var fs = client.OpenRead(remoteFile))
  3602. {
  3603. Assert.AreEqual(seekOffset + writeBuffer.Length, fs.Length);
  3604. Assert.AreEqual(0x04, fs.ReadByte());
  3605. var soughtOverReadBufferffer = new byte[seekOffset - 1];
  3606. Assert.AreEqual(soughtOverReadBufferffer.Length, fs.Read(soughtOverReadBufferffer, offset: 0, soughtOverReadBufferffer.Length));
  3607. Assert.IsTrue(new byte[soughtOverReadBufferffer.Length].IsEqualTo(soughtOverReadBufferffer));
  3608. var readBuffer = new byte[writeBuffer.Length];
  3609. Assert.AreEqual(readBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  3610. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  3611. // Ensure we've reached end of the stream
  3612. Assert.AreEqual(-1, fs.ReadByte());
  3613. }
  3614. client.DeleteFile(remoteFile);
  3615. // create single-byte file
  3616. using (var fs = client.OpenWrite(remoteFile))
  3617. {
  3618. fs.WriteByte(0x04);
  3619. }
  3620. // seek beyond EOF and beyond buffer size
  3621. // write less bytes than buffer size
  3622. seekOffset = 700L;
  3623. // buffer holding the data that we'll write to the file
  3624. writeBuffer = GenerateRandom(size: 4);
  3625. using (var fs = client.OpenWrite(remoteFile))
  3626. {
  3627. var newPosition = fs.Seek(seekOffset, SeekOrigin.Begin);
  3628. Assert.AreEqual(seekOffset, newPosition);
  3629. Assert.AreEqual(seekOffset, fs.Position);
  3630. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3631. }
  3632. using (var fs = client.OpenRead(remoteFile))
  3633. {
  3634. Assert.AreEqual(seekOffset + writeBuffer.Length, fs.Length);
  3635. Assert.AreEqual(0x04, fs.ReadByte());
  3636. var soughtOverReadBufferffer = new byte[seekOffset - 1];
  3637. Assert.AreEqual(soughtOverReadBufferffer.Length, fs.Read(soughtOverReadBufferffer, offset: 0, soughtOverReadBufferffer.Length));
  3638. Assert.IsTrue(new byte[soughtOverReadBufferffer.Length].IsEqualTo(soughtOverReadBufferffer));
  3639. var readBuffer = new byte[writeBuffer.Length];
  3640. Assert.AreEqual(readBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  3641. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  3642. // Ensure we've reached end of the stream
  3643. Assert.AreEqual(-1, fs.ReadByte());
  3644. }
  3645. client.DeleteFile(remoteFile);
  3646. // create single-byte file
  3647. using (var fs = client.OpenWrite(remoteFile))
  3648. {
  3649. fs.WriteByte(0x04);
  3650. }
  3651. // seek beyond EOF but not beyond buffer size
  3652. // write more bytes than buffer size
  3653. writeBuffer = GenerateRandom(size: 600);
  3654. using (var fs = client.OpenWrite(remoteFile))
  3655. {
  3656. var newPosition = fs.Seek(offset: 3L, SeekOrigin.Begin);
  3657. Assert.AreEqual(3, newPosition);
  3658. Assert.AreEqual(3, fs.Position);
  3659. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3660. }
  3661. using (var fs = client.OpenRead(remoteFile))
  3662. {
  3663. Assert.AreEqual(3 + writeBuffer.Length, fs.Length);
  3664. Assert.AreEqual(0x04, fs.ReadByte());
  3665. Assert.AreEqual(0x00, fs.ReadByte());
  3666. Assert.AreEqual(0x00, fs.ReadByte());
  3667. var readBuffer = new byte[writeBuffer.Length];
  3668. Assert.AreEqual(writeBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  3669. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  3670. // Ensure we've reached end of the stream
  3671. Assert.AreEqual(-1, fs.ReadByte());
  3672. }
  3673. client.DeleteFile(remoteFile);
  3674. // create single-byte file
  3675. using (var fs = client.OpenWrite(remoteFile))
  3676. {
  3677. fs.WriteByte(0x04);
  3678. }
  3679. // seek beyond EOF and beyond buffer size
  3680. // write more bytes than buffer size
  3681. writeBuffer = GenerateRandom(size: 600);
  3682. using (var fs = client.OpenWrite(remoteFile))
  3683. {
  3684. var newPosition = fs.Seek(offset: 550, SeekOrigin.Begin);
  3685. Assert.AreEqual(550, newPosition);
  3686. Assert.AreEqual(550, fs.Position);
  3687. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3688. }
  3689. using (var fs = client.OpenRead(remoteFile))
  3690. {
  3691. Assert.AreEqual(550 + writeBuffer.Length, fs.Length);
  3692. Assert.AreEqual(0x04, fs.ReadByte());
  3693. var soughtOverReadBuffer = new byte[550 - 1];
  3694. Assert.AreEqual(550 - 1, fs.Read(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length));
  3695. Assert.IsTrue(new byte[550 - 1].IsEqualTo(soughtOverReadBuffer));
  3696. var readBuffer = new byte[writeBuffer.Length];
  3697. Assert.AreEqual(writeBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  3698. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  3699. // Ensure we've reached end of the stream
  3700. Assert.AreEqual(-1, fs.ReadByte());
  3701. }
  3702. }
  3703. finally
  3704. {
  3705. if (client.Exists(remoteFile))
  3706. {
  3707. client.DeleteFile(remoteFile);
  3708. }
  3709. }
  3710. }
  3711. }
  3712. [TestMethod]
  3713. public void Sftp_SftpFileStream_Seek_BeyondEndOfFile_SeekOriginEnd()
  3714. {
  3715. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3716. {
  3717. client.BufferSize = 500;
  3718. client.Connect();
  3719. var remoteFile = GenerateUniqueRemoteFileName();
  3720. if (client.Exists(remoteFile))
  3721. {
  3722. client.DeleteFile(remoteFile);
  3723. }
  3724. try
  3725. {
  3726. // create single-byte file
  3727. using (var fs = client.OpenWrite(remoteFile))
  3728. {
  3729. fs.WriteByte(0x04);
  3730. }
  3731. // seek beyond EOF but not beyond buffer size
  3732. // do not write anything
  3733. using (var fs = client.OpenWrite(remoteFile))
  3734. {
  3735. var newPosition = fs.Seek(offset: 3L, SeekOrigin.End);
  3736. Assert.AreEqual(4, newPosition);
  3737. Assert.AreEqual(4, fs.Position);
  3738. }
  3739. using (var fs = client.OpenRead(remoteFile))
  3740. {
  3741. Assert.AreEqual(1, fs.Length);
  3742. Assert.AreEqual(0x04, fs.ReadByte());
  3743. // Ensure we've reached end of the stream
  3744. Assert.AreEqual(-1, fs.ReadByte());
  3745. }
  3746. client.DeleteFile(remoteFile);
  3747. // create single-byte file
  3748. using (var fs = client.OpenWrite(remoteFile))
  3749. {
  3750. fs.WriteByte(0x04);
  3751. }
  3752. // seek beyond EOF and beyond buffer size
  3753. // do not write anything
  3754. using (var fs = client.OpenWrite(remoteFile))
  3755. {
  3756. var newPosition = fs.Seek(offset: 700L, SeekOrigin.End);
  3757. Assert.AreEqual(701, newPosition);
  3758. Assert.AreEqual(701, fs.Position);
  3759. }
  3760. using (var fs = client.OpenRead(remoteFile))
  3761. {
  3762. Assert.AreEqual(1, fs.Length);
  3763. Assert.AreEqual(0x04, fs.ReadByte());
  3764. // Ensure we've reached end of the stream
  3765. Assert.AreEqual(-1, fs.ReadByte());
  3766. }
  3767. client.DeleteFile(remoteFile);
  3768. // create single-byte file
  3769. using (var fs = client.OpenWrite(remoteFile))
  3770. {
  3771. fs.WriteByte(0x04);
  3772. }
  3773. // seek beyond EOF but not beyond buffer size
  3774. // write less bytes than buffer size
  3775. var seekOffset = 3L;
  3776. // buffer holding the data that we'll write to the file
  3777. var writeBuffer = GenerateRandom(size: 7);
  3778. using (var fs = client.OpenWrite(remoteFile))
  3779. {
  3780. var newPosition = fs.Seek(seekOffset, SeekOrigin.End);
  3781. Assert.AreEqual(4, newPosition);
  3782. Assert.AreEqual(4, fs.Position);
  3783. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3784. }
  3785. using (var fs = client.OpenRead(remoteFile))
  3786. {
  3787. Assert.AreEqual(1 + seekOffset + writeBuffer.Length, fs.Length);
  3788. Assert.AreEqual(0x04, fs.ReadByte());
  3789. var soughtOverReadBuffer = new byte[seekOffset];
  3790. Assert.AreEqual(soughtOverReadBuffer.Length, fs.Read(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length));
  3791. Assert.IsTrue(new byte[soughtOverReadBuffer.Length].IsEqualTo(soughtOverReadBuffer));
  3792. var readBuffer = new byte[writeBuffer.Length];
  3793. Assert.AreEqual(readBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  3794. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  3795. // Ensure we've reached end of the stream
  3796. Assert.AreEqual(-1, fs.ReadByte());
  3797. }
  3798. client.DeleteFile(remoteFile);
  3799. // create single-byte file
  3800. using (var fs = client.OpenWrite(remoteFile))
  3801. {
  3802. fs.WriteByte(0x04);
  3803. }
  3804. // seek beyond EOF and beyond buffer size
  3805. // write less bytes than buffer size
  3806. seekOffset = 700L;
  3807. // buffer holding the data that we'll write to the file
  3808. writeBuffer = GenerateRandom(size: 4);
  3809. using (var fs = client.OpenWrite(remoteFile))
  3810. {
  3811. var newPosition = fs.Seek(seekOffset, SeekOrigin.End);
  3812. Assert.AreEqual(1 + seekOffset, newPosition);
  3813. Assert.AreEqual(1 + seekOffset, fs.Position);
  3814. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3815. }
  3816. using (var fs = client.OpenRead(remoteFile))
  3817. {
  3818. Assert.AreEqual(1 + seekOffset + writeBuffer.Length, fs.Length);
  3819. Assert.AreEqual(0x04, fs.ReadByte());
  3820. var soughtOverReadBuffer = new byte[seekOffset];
  3821. Assert.AreEqual(soughtOverReadBuffer.Length, fs.Read(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length));
  3822. Assert.IsTrue(new byte[soughtOverReadBuffer.Length].IsEqualTo(soughtOverReadBuffer));
  3823. var readBuffer = new byte[writeBuffer.Length];
  3824. Assert.AreEqual(readBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  3825. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  3826. // Ensure we've reached end of the stream
  3827. Assert.AreEqual(-1, fs.ReadByte());
  3828. }
  3829. client.DeleteFile(remoteFile);
  3830. // create single-byte file
  3831. using (var fs = client.OpenWrite(remoteFile))
  3832. {
  3833. fs.WriteByte(0x04);
  3834. }
  3835. // seek beyond EOF but not beyond buffer size
  3836. // write more bytes than buffer size
  3837. seekOffset = 3L;
  3838. writeBuffer = GenerateRandom(size: 600);
  3839. using (var fs = client.OpenWrite(remoteFile))
  3840. {
  3841. var newPosition = fs.Seek(seekOffset, SeekOrigin.End);
  3842. Assert.AreEqual(1 + seekOffset, newPosition);
  3843. Assert.AreEqual(1 + seekOffset, fs.Position);
  3844. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3845. }
  3846. using (var fs = client.OpenRead(remoteFile))
  3847. {
  3848. Assert.AreEqual(1 + seekOffset + writeBuffer.Length, fs.Length);
  3849. Assert.AreEqual(0x04, fs.ReadByte());
  3850. var soughtOverReadBuffer = new byte[seekOffset];
  3851. Assert.AreEqual(soughtOverReadBuffer.Length, fs.Read(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length));
  3852. Assert.IsTrue(new byte[soughtOverReadBuffer.Length].IsEqualTo(soughtOverReadBuffer));
  3853. var readBuffer = new byte[writeBuffer.Length];
  3854. Assert.AreEqual(writeBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  3855. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  3856. // Ensure we've reached end of the stream
  3857. Assert.AreEqual(-1, fs.ReadByte());
  3858. }
  3859. client.DeleteFile(remoteFile);
  3860. // create single-byte file
  3861. using (var fs = client.OpenWrite(remoteFile))
  3862. {
  3863. fs.WriteByte(0x04);
  3864. }
  3865. // seek beyond EOF and beyond buffer size
  3866. // write more bytes than buffer size
  3867. seekOffset = 550L;
  3868. writeBuffer = GenerateRandom(size: 600);
  3869. using (var fs = client.OpenWrite(remoteFile))
  3870. {
  3871. var newPosition = fs.Seek(seekOffset, SeekOrigin.End);
  3872. Assert.AreEqual(1 + seekOffset, newPosition);
  3873. Assert.AreEqual(1 + seekOffset, fs.Position);
  3874. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3875. }
  3876. using (var fs = client.OpenRead(remoteFile))
  3877. {
  3878. Assert.AreEqual(1 + seekOffset + writeBuffer.Length, fs.Length);
  3879. Assert.AreEqual(0x04, fs.ReadByte());
  3880. var soughtOverReadBuffer = new byte[seekOffset];
  3881. Assert.AreEqual(soughtOverReadBuffer.Length, fs.Read(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length));
  3882. Assert.IsTrue(new byte[soughtOverReadBuffer.Length].IsEqualTo(soughtOverReadBuffer));
  3883. var readBuffer = new byte[writeBuffer.Length];
  3884. Assert.AreEqual(writeBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  3885. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  3886. // Ensure we've reached end of the stream
  3887. Assert.AreEqual(-1, fs.ReadByte());
  3888. }
  3889. }
  3890. finally
  3891. {
  3892. if (client.Exists(remoteFile))
  3893. {
  3894. client.DeleteFile(remoteFile);
  3895. }
  3896. }
  3897. }
  3898. }
  3899. [TestMethod]
  3900. public void Sftp_SftpFileStream_Seek_NegativeOffSet_SeekOriginEnd()
  3901. {
  3902. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3903. {
  3904. client.BufferSize = 500;
  3905. client.Connect();
  3906. var remoteFile = GenerateUniqueRemoteFileName();
  3907. if (client.Exists(remoteFile))
  3908. {
  3909. client.DeleteFile(remoteFile);
  3910. }
  3911. try
  3912. {
  3913. using (var fs = client.OpenWrite(remoteFile))
  3914. {
  3915. fs.WriteByte(0x04);
  3916. fs.WriteByte(0x07);
  3917. fs.WriteByte(0x05);
  3918. }
  3919. // seek within file and not beyond buffer size
  3920. // do not write anything
  3921. using (var fs = client.OpenWrite(remoteFile))
  3922. {
  3923. var newPosition = fs.Seek(offset: -2L, SeekOrigin.End);
  3924. Assert.AreEqual(1, newPosition);
  3925. Assert.AreEqual(1, fs.Position);
  3926. }
  3927. using (var fs = client.OpenRead(remoteFile))
  3928. {
  3929. Assert.AreEqual(3, fs.Length);
  3930. Assert.AreEqual(0x04, fs.ReadByte());
  3931. Assert.AreEqual(0x07, fs.ReadByte());
  3932. Assert.AreEqual(0x05, fs.ReadByte());
  3933. // Ensure we've reached end of the stream
  3934. Assert.AreEqual(-1, fs.ReadByte());
  3935. }
  3936. client.DeleteFile(remoteFile);
  3937. // buffer holding the data that we'll write to the file
  3938. var writeBuffer = GenerateRandom(size: (int) client.BufferSize + 200);
  3939. using (var fs = client.OpenWrite(remoteFile))
  3940. {
  3941. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3942. }
  3943. // seek within EOF and beyond buffer size
  3944. // do not write anything
  3945. using (var fs = client.OpenWrite(remoteFile))
  3946. {
  3947. var newPosition = fs.Seek(offset: -100L, SeekOrigin.End);
  3948. Assert.AreEqual(600, newPosition);
  3949. Assert.AreEqual(600, fs.Position);
  3950. }
  3951. using (var fs = client.OpenRead(remoteFile))
  3952. {
  3953. Assert.AreEqual(writeBuffer.Length, fs.Length);
  3954. var readBuffer = new byte[writeBuffer.Length];
  3955. Assert.AreEqual(writeBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  3956. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  3957. // Ensure we've reached end of the stream
  3958. Assert.AreEqual(-1, fs.ReadByte());
  3959. }
  3960. client.DeleteFile(remoteFile);
  3961. // seek within EOF and within buffer size
  3962. // write less bytes than buffer size
  3963. using (var fs = client.OpenWrite(remoteFile))
  3964. {
  3965. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3966. var newPosition = fs.Seek(offset: -3, SeekOrigin.End);
  3967. Assert.AreEqual(697, newPosition);
  3968. Assert.AreEqual(697, fs.Position);
  3969. fs.WriteByte(0x01);
  3970. fs.WriteByte(0x05);
  3971. fs.WriteByte(0x04);
  3972. fs.WriteByte(0x07);
  3973. }
  3974. using (var fs = client.OpenRead(remoteFile))
  3975. {
  3976. Assert.AreEqual(writeBuffer.Length + 1, fs.Length);
  3977. var readBuffer = new byte[writeBuffer.Length - 3];
  3978. Assert.AreEqual(readBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  3979. Assert.IsTrue(readBuffer.SequenceEqual(writeBuffer.Take(readBuffer.Length)));
  3980. Assert.AreEqual(0x01, fs.ReadByte());
  3981. Assert.AreEqual(0x05, fs.ReadByte());
  3982. Assert.AreEqual(0x04, fs.ReadByte());
  3983. Assert.AreEqual(0x07, fs.ReadByte());
  3984. // Ensure we've reached end of the stream
  3985. Assert.AreEqual(-1, fs.ReadByte());
  3986. }
  3987. client.DeleteFile(remoteFile);
  3988. // buffer holding the data that we'll write to the file
  3989. writeBuffer = GenerateRandom(size: (int) client.BufferSize * 4);
  3990. // seek within EOF and beyond buffer size
  3991. // write less bytes than buffer size
  3992. using (var fs = client.OpenWrite(remoteFile))
  3993. {
  3994. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3995. var newPosition = fs.Seek(offset: -(client.BufferSize * 2), SeekOrigin.End);
  3996. Assert.AreEqual(1000, newPosition);
  3997. Assert.AreEqual(1000, fs.Position);
  3998. fs.WriteByte(0x01);
  3999. fs.WriteByte(0x05);
  4000. fs.WriteByte(0x04);
  4001. fs.WriteByte(0x07);
  4002. }
  4003. using (var fs = client.OpenRead(remoteFile))
  4004. {
  4005. Assert.AreEqual(writeBuffer.Length, fs.Length);
  4006. // First part of file should not have been touched
  4007. var readBuffer = new byte[(int) client.BufferSize * 2];
  4008. Assert.AreEqual(readBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  4009. Assert.IsTrue(readBuffer.SequenceEqual(writeBuffer.Take(readBuffer.Length)));
  4010. // Check part that should have been updated
  4011. Assert.AreEqual(0x01, fs.ReadByte());
  4012. Assert.AreEqual(0x05, fs.ReadByte());
  4013. Assert.AreEqual(0x04, fs.ReadByte());
  4014. Assert.AreEqual(0x07, fs.ReadByte());
  4015. // Remaining bytes should not have been touched
  4016. readBuffer = new byte[((int) client.BufferSize * 2) - 4];
  4017. Assert.AreEqual(readBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  4018. Assert.IsTrue(readBuffer.SequenceEqual(writeBuffer.Skip(((int)client.BufferSize * 2) + 4).Take(readBuffer.Length)));
  4019. // Ensure we've reached end of the stream
  4020. Assert.AreEqual(-1, fs.ReadByte());
  4021. }
  4022. }
  4023. finally
  4024. {
  4025. if (client.Exists(remoteFile))
  4026. {
  4027. client.DeleteFile(remoteFile);
  4028. }
  4029. }
  4030. }
  4031. }
  4032. /// https://github.com/sshnet/SSH.NET/issues/253
  4033. [TestMethod]
  4034. public void Sftp_SftpFileStream_Seek_Issue253()
  4035. {
  4036. var buf = Encoding.UTF8.GetBytes("123456");
  4037. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4038. {
  4039. client.Connect();
  4040. var remoteFile = GenerateUniqueRemoteFileName();
  4041. if (client.Exists(remoteFile))
  4042. {
  4043. client.DeleteFile(remoteFile);
  4044. }
  4045. try
  4046. {
  4047. using (var ws = client.OpenWrite(remoteFile))
  4048. {
  4049. ws.Write(buf, offset: 0, count: 3);
  4050. }
  4051. using (var ws = client.OpenWrite(remoteFile))
  4052. {
  4053. var newPosition = ws.Seek(offset: 3, SeekOrigin.Begin);
  4054. Assert.AreEqual(3, newPosition);
  4055. Assert.AreEqual(3, ws.Position);
  4056. ws.Write(buf, 3, 3);
  4057. }
  4058. var actual = client.ReadAllText(remoteFile, Encoding.UTF8);
  4059. Assert.AreEqual("123456", actual);
  4060. }
  4061. finally
  4062. {
  4063. if (client.Exists(remoteFile))
  4064. {
  4065. client.DeleteFile(remoteFile);
  4066. }
  4067. }
  4068. }
  4069. }
  4070. [TestMethod]
  4071. public void Sftp_SftpFileStream_Seek_WithinReadBuffer()
  4072. {
  4073. var originalContent = GenerateRandom(size: 800);
  4074. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4075. {
  4076. client.BufferSize = 500;
  4077. client.Connect();
  4078. var remoteFile = GenerateUniqueRemoteFileName();
  4079. if (client.Exists(remoteFile))
  4080. {
  4081. client.DeleteFile(remoteFile);
  4082. }
  4083. try
  4084. {
  4085. using (var fs = client.OpenWrite(remoteFile))
  4086. {
  4087. fs.Write(originalContent, offset: 0, originalContent.Length);
  4088. }
  4089. using (var fs = client.OpenRead(remoteFile))
  4090. {
  4091. var readBuffer = new byte[200];
  4092. Assert.AreEqual(readBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  4093. var newPosition = fs.Seek(offset: 3L, SeekOrigin.Begin);
  4094. Assert.AreEqual(3L, newPosition);
  4095. Assert.AreEqual(3L, fs.Position);
  4096. }
  4097. client.DeleteFile(remoteFile);
  4098. #region Seek beyond EOF and beyond buffer size do not write anything
  4099. // create single-byte file
  4100. using (var fs = client.OpenWrite(remoteFile))
  4101. {
  4102. fs.WriteByte(0x04);
  4103. }
  4104. using (var fs = client.OpenRead(remoteFile))
  4105. {
  4106. Assert.AreEqual(1, fs.Length);
  4107. Assert.AreEqual(0x04, fs.ReadByte());
  4108. // Ensure we've reached end of the stream
  4109. Assert.AreEqual(-1, fs.ReadByte());
  4110. }
  4111. using (var fs = client.OpenWrite(remoteFile))
  4112. {
  4113. var newPosition = fs.Seek(offset: 700L, SeekOrigin.Begin);
  4114. Assert.AreEqual(700L, newPosition);
  4115. Assert.AreEqual(700L, fs.Position);
  4116. }
  4117. using (var fs = client.OpenRead(remoteFile))
  4118. {
  4119. Assert.AreEqual(1, fs.Length);
  4120. Assert.AreEqual(0x04, fs.ReadByte());
  4121. // Ensure we've reached end of the stream
  4122. Assert.AreEqual(-1, fs.ReadByte());
  4123. }
  4124. client.DeleteFile(remoteFile);
  4125. #endregion Seek beyond EOF and beyond buffer size do not write anything
  4126. #region Seek beyond EOF but not beyond buffer size and write less bytes than buffer size
  4127. // create single-byte file
  4128. using (var fs = client.OpenWrite(remoteFile))
  4129. {
  4130. fs.WriteByte(0x04);
  4131. }
  4132. var seekOffset = 3L;
  4133. var writeBuffer = GenerateRandom(size: 7);
  4134. using (var fs = client.OpenWrite(remoteFile))
  4135. {
  4136. var newPosition = fs.Seek(seekOffset, SeekOrigin.Begin);
  4137. Assert.AreEqual(seekOffset, newPosition);
  4138. Assert.AreEqual(seekOffset, fs.Position);
  4139. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  4140. }
  4141. using (var fs = client.OpenRead(remoteFile))
  4142. {
  4143. Assert.AreEqual(seekOffset + writeBuffer.Length, fs.Length);
  4144. Assert.AreEqual(0x04, fs.ReadByte());
  4145. var soughtOverReadBuffer = new byte[seekOffset - 1];
  4146. Assert.AreEqual(soughtOverReadBuffer.Length, fs.Read(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length));
  4147. Assert.IsTrue(new byte[soughtOverReadBuffer.Length].IsEqualTo(soughtOverReadBuffer));
  4148. var readBuffer = new byte[writeBuffer.Length];
  4149. Assert.AreEqual(readBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  4150. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  4151. // Ensure we've reached end of the stream
  4152. Assert.AreEqual(-1, fs.ReadByte());
  4153. }
  4154. client.DeleteFile(remoteFile);
  4155. #endregion Seek beyond EOF but not beyond buffer size and write less bytes than buffer size
  4156. #region Seek beyond EOF and beyond buffer size and write less bytes than buffer size
  4157. // create single-byte file
  4158. using (var fs = client.OpenWrite(remoteFile))
  4159. {
  4160. fs.WriteByte(0x04);
  4161. }
  4162. seekOffset = 700L;
  4163. writeBuffer = GenerateRandom(size: 4);
  4164. using (var fs = client.OpenWrite(remoteFile))
  4165. {
  4166. var newPosition = fs.Seek(seekOffset, SeekOrigin.Begin);
  4167. Assert.AreEqual(seekOffset, newPosition);
  4168. Assert.AreEqual(seekOffset, fs.Position);
  4169. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  4170. }
  4171. using (var fs = client.OpenRead(remoteFile))
  4172. {
  4173. Assert.AreEqual(seekOffset + writeBuffer.Length, fs.Length);
  4174. Assert.AreEqual(0x04, fs.ReadByte());
  4175. var soughtOverReadBufferffer = new byte[seekOffset - 1];
  4176. Assert.AreEqual(soughtOverReadBufferffer.Length, fs.Read(soughtOverReadBufferffer, offset: 0, soughtOverReadBufferffer.Length));
  4177. Assert.IsTrue(new byte[soughtOverReadBufferffer.Length].IsEqualTo(soughtOverReadBufferffer));
  4178. var readBuffer = new byte[writeBuffer.Length];
  4179. Assert.AreEqual(readBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  4180. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  4181. // Ensure we've reached end of the stream
  4182. Assert.AreEqual(-1, fs.ReadByte());
  4183. }
  4184. client.DeleteFile(remoteFile);
  4185. #endregion Seek beyond EOF and beyond buffer size and write less bytes than buffer size
  4186. #region Seek beyond EOF but not beyond buffer size and write more bytes than buffer size
  4187. // create single-byte file
  4188. using (var fs = client.OpenWrite(remoteFile))
  4189. {
  4190. fs.WriteByte(0x04);
  4191. }
  4192. seekOffset = 3L;
  4193. writeBuffer = GenerateRandom(size: 600);
  4194. using (var fs = client.OpenWrite(remoteFile))
  4195. {
  4196. var newPosition = fs.Seek(seekOffset, SeekOrigin.Begin);
  4197. Assert.AreEqual(seekOffset, newPosition);
  4198. Assert.AreEqual(seekOffset, fs.Position);
  4199. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  4200. }
  4201. using (var fs = client.OpenRead(remoteFile))
  4202. {
  4203. Assert.AreEqual(seekOffset + writeBuffer.Length, fs.Length);
  4204. Assert.AreEqual(0x04, fs.ReadByte());
  4205. Assert.AreEqual(0x00, fs.ReadByte());
  4206. Assert.AreEqual(0x00, fs.ReadByte());
  4207. var readBuffer = new byte[writeBuffer.Length];
  4208. Assert.AreEqual(writeBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  4209. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  4210. // Ensure we've reached end of the stream
  4211. Assert.AreEqual(-1, fs.ReadByte());
  4212. }
  4213. client.DeleteFile(remoteFile);
  4214. #endregion Seek beyond EOF but not beyond buffer size and write more bytes than buffer size
  4215. #region Seek beyond EOF and beyond buffer size and write more bytes than buffer size
  4216. // create single-byte file
  4217. using (var fs = client.OpenWrite(remoteFile))
  4218. {
  4219. fs.WriteByte(0x04);
  4220. }
  4221. seekOffset = 550L;
  4222. writeBuffer = GenerateRandom(size: 600);
  4223. using (var fs = client.OpenWrite(remoteFile))
  4224. {
  4225. var newPosition = fs.Seek(seekOffset, SeekOrigin.Begin);
  4226. Assert.AreEqual(seekOffset, newPosition);
  4227. Assert.AreEqual(seekOffset, fs.Position);
  4228. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  4229. }
  4230. using (var fs = client.OpenRead(remoteFile))
  4231. {
  4232. Assert.AreEqual(seekOffset + writeBuffer.Length, fs.Length);
  4233. Assert.AreEqual(0x04, fs.ReadByte());
  4234. var soughtOverReadBufferffer = new byte[seekOffset - 1];
  4235. Assert.AreEqual(seekOffset - 1, fs.Read(soughtOverReadBufferffer, offset: 0, soughtOverReadBufferffer.Length));
  4236. Assert.IsTrue(new byte[seekOffset - 1].IsEqualTo(soughtOverReadBufferffer));
  4237. var readBuffer = new byte[writeBuffer.Length];
  4238. Assert.AreEqual(writeBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  4239. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  4240. // Ensure we've reached end of the stream
  4241. Assert.AreEqual(-1, fs.ReadByte());
  4242. }
  4243. client.DeleteFile(remoteFile);
  4244. #endregion Seek beyond EOF and beyond buffer size and write more bytes than buffer size
  4245. }
  4246. finally
  4247. {
  4248. if (client.Exists(remoteFile))
  4249. {
  4250. client.DeleteFile(remoteFile);
  4251. }
  4252. }
  4253. }
  4254. }
  4255. [TestMethod]
  4256. public void Sftp_SftpFileStream_SetLength_FileDoesNotExist()
  4257. {
  4258. var size = new Random().Next(500, 5000);
  4259. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4260. {
  4261. client.Connect();
  4262. var remoteFile = GenerateUniqueRemoteFileName();
  4263. if (client.Exists(remoteFile))
  4264. {
  4265. client.DeleteFile(remoteFile);
  4266. }
  4267. try
  4268. {
  4269. using (var s = client.Open(remoteFile, FileMode.Append, FileAccess.Write))
  4270. {
  4271. s.SetLength(size);
  4272. }
  4273. Assert.IsTrue(client.Exists(remoteFile));
  4274. var attributes = client.GetAttributes(remoteFile);
  4275. Assert.IsTrue(attributes.IsRegularFile);
  4276. Assert.AreEqual(size, attributes.Size);
  4277. using (var downloaded = new MemoryStream())
  4278. {
  4279. client.DownloadFile(remoteFile, downloaded);
  4280. downloaded.Position = 0;
  4281. Assert.AreEqual(CreateHash(new byte[size]), CreateHash(downloaded));
  4282. }
  4283. }
  4284. finally
  4285. {
  4286. if (client.Exists(remoteFile))
  4287. {
  4288. client.DeleteFile(remoteFile);
  4289. }
  4290. }
  4291. }
  4292. }
  4293. [TestMethod]
  4294. public void Sftp_Open_Append_Write_ExistingFile()
  4295. {
  4296. const int fileSize = 5 * 1024;
  4297. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4298. using (var input = CreateMemoryStream(fileSize))
  4299. {
  4300. input.Position = 0;
  4301. client.Connect();
  4302. var remoteFile = GenerateUniqueRemoteFileName();
  4303. if (client.Exists(remoteFile))
  4304. {
  4305. client.DeleteFile(remoteFile);
  4306. }
  4307. try
  4308. {
  4309. client.UploadFile(input, remoteFile);
  4310. using (var s = client.Open(remoteFile, FileMode.Append, FileAccess.Write))
  4311. {
  4312. var buffer = new byte[] { 0x05, 0x0f, 0x0d, 0x0a, 0x04 };
  4313. s.Write(buffer, offset: 0, buffer.Length);
  4314. input.Write(buffer, offset: 0, buffer.Length);
  4315. }
  4316. using (var downloaded = new MemoryStream())
  4317. {
  4318. client.DownloadFile(remoteFile, downloaded);
  4319. input.Position = 0;
  4320. downloaded.Position = 0;
  4321. Assert.AreEqual(CreateHash(input), CreateHash(downloaded));
  4322. }
  4323. }
  4324. finally
  4325. {
  4326. if (client.Exists(remoteFile))
  4327. {
  4328. client.DeleteFile(remoteFile);
  4329. }
  4330. }
  4331. }
  4332. }
  4333. [TestMethod]
  4334. public void Sftp_Open_Append_Write_FileDoesNotExist()
  4335. {
  4336. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4337. {
  4338. client.Connect();
  4339. var remoteFile = GenerateUniqueRemoteFileName();
  4340. if (client.Exists(remoteFile))
  4341. {
  4342. client.DeleteFile(remoteFile);
  4343. }
  4344. try
  4345. {
  4346. #region Verify if merely opening the file for append creates a zero-byte file
  4347. using (client.Open(remoteFile, FileMode.Append, FileAccess.Write))
  4348. {
  4349. }
  4350. Assert.IsTrue(client.Exists(remoteFile));
  4351. var attributes = client.GetAttributes(remoteFile);
  4352. Assert.IsTrue(attributes.IsRegularFile);
  4353. Assert.AreEqual(0L, attributes.Size);
  4354. #endregion Verify if merely opening the file for append creates it
  4355. client.DeleteFile(remoteFile);
  4356. #region Verify if content is actually written to the file
  4357. var content = GenerateRandom(size: 100);
  4358. using (var s = client.Open(remoteFile, FileMode.Append, FileAccess.Write))
  4359. {
  4360. s.Write(content, offset: 0, content.Length);
  4361. }
  4362. using (var downloaded = new MemoryStream())
  4363. {
  4364. client.DownloadFile(remoteFile, downloaded);
  4365. downloaded.Position = 0;
  4366. Assert.AreEqual(CreateHash(content), CreateHash(downloaded));
  4367. }
  4368. #endregion Verify if content is actually written to the file
  4369. }
  4370. finally
  4371. {
  4372. if (client.Exists(remoteFile))
  4373. {
  4374. client.DeleteFile(remoteFile);
  4375. }
  4376. }
  4377. }
  4378. }
  4379. [TestMethod]
  4380. public void Sftp_Open_PathAndMode_ModeIsCreate_FileDoesNotExist()
  4381. {
  4382. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4383. {
  4384. client.Connect();
  4385. var remoteFile = GenerateUniqueRemoteFileName();
  4386. if (client.Exists(remoteFile))
  4387. {
  4388. client.DeleteFile(remoteFile);
  4389. }
  4390. try
  4391. {
  4392. #region Verify if merely opening the file for create creates a zero-byte file
  4393. using (client.Open(remoteFile, FileMode.Create))
  4394. {
  4395. }
  4396. Assert.IsTrue(client.Exists(remoteFile));
  4397. var attributes = client.GetAttributes(remoteFile);
  4398. Assert.IsTrue(attributes.IsRegularFile);
  4399. Assert.AreEqual(0L, attributes.Size);
  4400. #endregion Verify if merely opening the file for create creates a zero-byte file
  4401. client.DeleteFile(remoteFile);
  4402. #region Verify if content is actually written to the file
  4403. var content = GenerateRandom(size: 100);
  4404. using (var s = client.Open(remoteFile, FileMode.Create))
  4405. {
  4406. s.Write(content, offset: 0, content.Length);
  4407. }
  4408. using (var downloaded = new MemoryStream())
  4409. {
  4410. client.DownloadFile(remoteFile, downloaded);
  4411. downloaded.Position = 0;
  4412. Assert.AreEqual(CreateHash(content), CreateHash(downloaded));
  4413. }
  4414. #endregion Verify if content is actually written to the file
  4415. }
  4416. finally
  4417. {
  4418. if (client.Exists(remoteFile))
  4419. {
  4420. client.DeleteFile(remoteFile);
  4421. }
  4422. }
  4423. }
  4424. }
  4425. [TestMethod]
  4426. public void Sftp_Open_PathAndMode_ModeIsCreate_ExistingFile()
  4427. {
  4428. const int fileSize = 5 * 1024;
  4429. var newContent = new byte[] { 0x07, 0x03, 0x02, 0x0b };
  4430. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4431. using (var input = CreateMemoryStream(fileSize))
  4432. {
  4433. client.Connect();
  4434. var remoteFile = GenerateUniqueRemoteFileName();
  4435. if (client.Exists(remoteFile))
  4436. {
  4437. client.DeleteFile(remoteFile);
  4438. }
  4439. try
  4440. {
  4441. input.Position = 0;
  4442. client.UploadFile(input, remoteFile);
  4443. using (var stream = client.Open(remoteFile, FileMode.Create))
  4444. {
  4445. // Verify if merely opening the file for create overwrites the file
  4446. var attributes = client.GetAttributes(remoteFile);
  4447. Assert.IsTrue(attributes.IsRegularFile);
  4448. Assert.AreEqual(0L, attributes.Size);
  4449. stream.Write(newContent, offset: 0, newContent.Length);
  4450. stream.Position = 0;
  4451. Assert.AreEqual(CreateHash(newContent), CreateHash(stream));
  4452. }
  4453. }
  4454. finally
  4455. {
  4456. if (client.Exists(remoteFile))
  4457. {
  4458. client.DeleteFile(remoteFile);
  4459. }
  4460. }
  4461. }
  4462. }
  4463. [TestMethod]
  4464. public void Sftp_Open_PathAndModeAndAccess_ModeIsCreate_AccessIsReadWrite_FileDoesNotExist()
  4465. {
  4466. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4467. {
  4468. client.Connect();
  4469. var remoteFile = GenerateUniqueRemoteFileName();
  4470. if (client.Exists(remoteFile))
  4471. {
  4472. client.DeleteFile(remoteFile);
  4473. }
  4474. try
  4475. {
  4476. #region Verify if merely opening the file for create creates a zero-byte file
  4477. using (client.Open(remoteFile, FileMode.Create, FileAccess.ReadWrite))
  4478. {
  4479. }
  4480. Assert.IsTrue(client.Exists(remoteFile));
  4481. var attributes = client.GetAttributes(remoteFile);
  4482. Assert.IsTrue(attributes.IsRegularFile);
  4483. Assert.AreEqual(0L, attributes.Size);
  4484. #endregion Verify if merely opening the file for create creates a zero-byte file
  4485. client.DeleteFile(remoteFile);
  4486. #region Verify if content is actually written to the file
  4487. var content = GenerateRandom(size: 100);
  4488. using (var s = client.Open(remoteFile, FileMode.Create, FileAccess.ReadWrite))
  4489. {
  4490. s.Write(content, offset: 0, content.Length);
  4491. }
  4492. using (var downloaded = new MemoryStream())
  4493. {
  4494. client.DownloadFile(remoteFile, downloaded);
  4495. downloaded.Position = 0;
  4496. Assert.AreEqual(CreateHash(content), CreateHash(downloaded));
  4497. }
  4498. #endregion Verify if content is actually written to the file
  4499. }
  4500. finally
  4501. {
  4502. if (client.Exists(remoteFile))
  4503. {
  4504. client.DeleteFile(remoteFile);
  4505. }
  4506. }
  4507. }
  4508. }
  4509. [TestMethod]
  4510. public void Sftp_Open_PathAndModeAndAccess_ModeIsCreate_AccessIsReadWrite_ExistingFile()
  4511. {
  4512. const int fileSize = 5 * 1024;
  4513. var newContent = new byte[] { 0x07, 0x03, 0x02, 0x0b };
  4514. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4515. using (var input = CreateMemoryStream(fileSize))
  4516. {
  4517. client.Connect();
  4518. var remoteFile = GenerateUniqueRemoteFileName();
  4519. if (client.Exists(remoteFile))
  4520. {
  4521. client.DeleteFile(remoteFile);
  4522. }
  4523. try
  4524. {
  4525. input.Position = 0;
  4526. client.UploadFile(input, remoteFile);
  4527. using (var stream = client.Open(remoteFile, FileMode.Create, FileAccess.ReadWrite))
  4528. {
  4529. // Verify if merely opening the file for create overwrites the file
  4530. var attributes = client.GetAttributes(remoteFile);
  4531. Assert.IsTrue(attributes.IsRegularFile);
  4532. Assert.AreEqual(0L, attributes.Size);
  4533. stream.Write(newContent, offset: 0, newContent.Length);
  4534. stream.Position = 0;
  4535. Assert.AreEqual(CreateHash(newContent), CreateHash(stream));
  4536. }
  4537. }
  4538. finally
  4539. {
  4540. if (client.Exists(remoteFile))
  4541. {
  4542. client.DeleteFile(remoteFile);
  4543. }
  4544. }
  4545. }
  4546. }
  4547. [TestMethod]
  4548. public void Sftp_Open_PathAndModeAndAccess_ModeIsCreate_AccessIsWrite_ExistingFile()
  4549. {
  4550. // use new content that contains less bytes than original content to
  4551. // verify whether file is first truncated
  4552. var originalContent = new byte[] { 0x05, 0x0f, 0x0d, 0x0a, 0x04 };
  4553. var newContent = new byte[] { 0x07, 0x03, 0x02, 0x0b };
  4554. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4555. {
  4556. client.Connect();
  4557. var remoteFile = GenerateUniqueRemoteFileName();
  4558. if (client.Exists(remoteFile))
  4559. {
  4560. client.DeleteFile(remoteFile);
  4561. }
  4562. try
  4563. {
  4564. client.WriteAllBytes(remoteFile, originalContent);
  4565. using (var s = client.Open(remoteFile, FileMode.Create, FileAccess.Write))
  4566. {
  4567. s.Write(newContent, offset: 0, newContent.Length);
  4568. }
  4569. using (var downloaded = new MemoryStream())
  4570. {
  4571. client.DownloadFile(remoteFile, downloaded);
  4572. downloaded.Position = 0;
  4573. Assert.AreEqual(CreateHash(newContent), CreateHash(downloaded));
  4574. }
  4575. }
  4576. finally
  4577. {
  4578. if (client.Exists(remoteFile))
  4579. {
  4580. client.DeleteFile(remoteFile);
  4581. }
  4582. }
  4583. }
  4584. }
  4585. [TestMethod]
  4586. public void Sftp_Open_PathAndModeAndAccess_ModeIsCreate_AccessIsWrite_FileDoesNotExist()
  4587. {
  4588. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4589. {
  4590. client.Connect();
  4591. var remoteFile = GenerateUniqueRemoteFileName();
  4592. if (client.Exists(remoteFile))
  4593. {
  4594. client.DeleteFile(remoteFile);
  4595. }
  4596. try
  4597. {
  4598. #region Verify if merely opening the file for create creates a zero-byte file
  4599. using (client.Open(remoteFile, FileMode.Create, FileAccess.Write))
  4600. {
  4601. }
  4602. Assert.IsTrue(client.Exists(remoteFile));
  4603. var attributes = client.GetAttributes(remoteFile);
  4604. Assert.IsTrue(attributes.IsRegularFile);
  4605. Assert.AreEqual(0L, attributes.Size);
  4606. #endregion Verify if merely opening the file for create creates a zero-byte file
  4607. client.DeleteFile(remoteFile);
  4608. #region Verify if content is actually written to the file
  4609. var content = GenerateRandom(size: 100);
  4610. using (var s = client.Open(remoteFile, FileMode.Create, FileAccess.Write))
  4611. {
  4612. s.Write(content, offset: 0, content.Length);
  4613. }
  4614. using (var downloaded = new MemoryStream())
  4615. {
  4616. client.DownloadFile(remoteFile, downloaded);
  4617. downloaded.Position = 0;
  4618. Assert.AreEqual(CreateHash(content), CreateHash(downloaded));
  4619. }
  4620. #endregion Verify if content is actually written to the file
  4621. }
  4622. finally
  4623. {
  4624. if (client.Exists(remoteFile))
  4625. {
  4626. client.DeleteFile(remoteFile);
  4627. }
  4628. }
  4629. }
  4630. }
  4631. [TestMethod]
  4632. public void Sftp_Open_CreateNew_Write_ExistingFile()
  4633. {
  4634. const int fileSize = 5 * 1024;
  4635. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4636. using (var input = CreateMemoryStream(fileSize))
  4637. {
  4638. client.Connect();
  4639. var remoteFile = GenerateUniqueRemoteFileName();
  4640. if (client.Exists(remoteFile))
  4641. {
  4642. client.DeleteFile(remoteFile);
  4643. }
  4644. input.Position = 0;
  4645. try
  4646. {
  4647. client.UploadFile(input, remoteFile);
  4648. Stream stream = null;
  4649. try
  4650. {
  4651. stream = client.Open(remoteFile, FileMode.CreateNew, FileAccess.Write);
  4652. Assert.Fail();
  4653. }
  4654. catch (SshException)
  4655. {
  4656. }
  4657. finally
  4658. {
  4659. stream?.Dispose();
  4660. }
  4661. // Verify that the file was not modified
  4662. using (var downloaded = new MemoryStream())
  4663. {
  4664. client.DownloadFile(remoteFile, downloaded);
  4665. input.Position = 0;
  4666. downloaded.Position = 0;
  4667. Assert.AreEqual(CreateHash(input), CreateHash(downloaded));
  4668. }
  4669. }
  4670. finally
  4671. {
  4672. if (client.Exists(remoteFile))
  4673. {
  4674. client.DeleteFile(remoteFile);
  4675. }
  4676. }
  4677. }
  4678. }
  4679. [TestMethod]
  4680. public void Sftp_Open_CreateNew_Write_FileDoesNotExist()
  4681. {
  4682. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4683. {
  4684. client.Connect();
  4685. var remoteFile = GenerateUniqueRemoteFileName();
  4686. if (client.Exists(remoteFile))
  4687. {
  4688. client.DeleteFile(remoteFile);
  4689. }
  4690. try
  4691. {
  4692. #region Verify if merely opening the file creates a zero-byte file
  4693. using (client.Open(remoteFile, FileMode.CreateNew, FileAccess.Write))
  4694. {
  4695. }
  4696. Assert.IsTrue(client.Exists(remoteFile));
  4697. var attributes = client.GetAttributes(remoteFile);
  4698. Assert.IsTrue(attributes.IsRegularFile);
  4699. Assert.AreEqual(0L, attributes.Size);
  4700. #endregion Verify if merely opening the file creates it
  4701. client.DeleteFile(remoteFile);
  4702. #region Verify if content is actually written to the file
  4703. var content = GenerateRandom(size: 100);
  4704. using (var s = client.Open(remoteFile, FileMode.CreateNew, FileAccess.Write))
  4705. {
  4706. s.Write(content, offset: 0, content.Length);
  4707. }
  4708. using (var downloaded = new MemoryStream())
  4709. {
  4710. client.DownloadFile(remoteFile, downloaded);
  4711. downloaded.Position = 0;
  4712. Assert.AreEqual(CreateHash(content), CreateHash(downloaded));
  4713. }
  4714. #endregion Verify if content is actually written to the file
  4715. }
  4716. finally
  4717. {
  4718. if (client.Exists(remoteFile))
  4719. {
  4720. client.DeleteFile(remoteFile);
  4721. }
  4722. }
  4723. }
  4724. }
  4725. [TestMethod]
  4726. public void Sftp_Open_Open_Write_ExistingFile()
  4727. {
  4728. // use new content that contains less bytes than original content to
  4729. // verify whether file is first truncated
  4730. var originalContent = new byte[] { 0x05, 0x0f, 0x0d, 0x0a, 0x04 };
  4731. var newContent = new byte[] { 0x07, 0x03, 0x02, 0x0b };
  4732. var expectedContent = new byte[] { 0x07, 0x03, 0x02, 0x0b, 0x04 };
  4733. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4734. {
  4735. client.Connect();
  4736. var remoteFile = GenerateUniqueRemoteFileName();
  4737. if (client.Exists(remoteFile))
  4738. {
  4739. client.DeleteFile(remoteFile);
  4740. }
  4741. try
  4742. {
  4743. client.WriteAllBytes(remoteFile, originalContent);
  4744. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.Write))
  4745. {
  4746. s.Write(newContent, offset: 0, newContent.Length);
  4747. }
  4748. using (var downloaded = new MemoryStream())
  4749. {
  4750. client.DownloadFile(remoteFile, downloaded);
  4751. downloaded.Position = 0;
  4752. Assert.AreEqual(CreateHash(expectedContent), CreateHash(downloaded));
  4753. }
  4754. }
  4755. finally
  4756. {
  4757. if (client.Exists(remoteFile))
  4758. {
  4759. client.DeleteFile(remoteFile);
  4760. }
  4761. }
  4762. }
  4763. }
  4764. [TestMethod]
  4765. public void Sftp_Open_Open_Write_FileDoesNotExist()
  4766. {
  4767. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4768. {
  4769. client.Connect();
  4770. var remoteFile = GenerateUniqueRemoteFileName();
  4771. if (client.Exists(remoteFile))
  4772. {
  4773. client.DeleteFile(remoteFile);
  4774. }
  4775. try
  4776. {
  4777. Stream stream = null;
  4778. try
  4779. {
  4780. stream = client.Open(remoteFile, FileMode.Open, FileAccess.Write);
  4781. Assert.Fail();
  4782. }
  4783. catch (SshException)
  4784. {
  4785. }
  4786. finally
  4787. {
  4788. stream?.Dispose();
  4789. }
  4790. Assert.IsFalse(client.Exists(remoteFile));
  4791. }
  4792. finally
  4793. {
  4794. if (client.Exists(remoteFile))
  4795. {
  4796. client.DeleteFile(remoteFile);
  4797. }
  4798. }
  4799. }
  4800. }
  4801. [TestMethod]
  4802. public void Sftp_Open_OpenOrCreate_Write_ExistingFile()
  4803. {
  4804. // use new content that contains less bytes than original content to
  4805. // verify whether file is first truncated
  4806. var originalContent = new byte[] { 0x05, 0x0f, 0x0d, 0x0a, 0x04 };
  4807. var newContent = new byte[] { 0x07, 0x03, 0x02, 0x0b };
  4808. var expectedContent = new byte[] { 0x07, 0x03, 0x02, 0x0b, 0x04 };
  4809. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4810. {
  4811. client.Connect();
  4812. var remoteFile = GenerateUniqueRemoteFileName();
  4813. if (client.Exists(remoteFile))
  4814. {
  4815. client.DeleteFile(remoteFile);
  4816. }
  4817. try
  4818. {
  4819. client.WriteAllBytes(remoteFile, originalContent);
  4820. using (var s = client.Open(remoteFile, FileMode.OpenOrCreate, FileAccess.Write))
  4821. {
  4822. s.Write(newContent, offset: 0, newContent.Length);
  4823. }
  4824. using (var downloaded = new MemoryStream())
  4825. {
  4826. client.DownloadFile(remoteFile, downloaded);
  4827. downloaded.Position = 0;
  4828. Assert.AreEqual(CreateHash(expectedContent), CreateHash(downloaded));
  4829. }
  4830. }
  4831. finally
  4832. {
  4833. if (client.Exists(remoteFile))
  4834. {
  4835. client.DeleteFile(remoteFile);
  4836. }
  4837. }
  4838. }
  4839. }
  4840. [TestMethod]
  4841. public void Sftp_Open_OpenOrCreate_Write_FileDoesNotExist()
  4842. {
  4843. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4844. {
  4845. client.Connect();
  4846. var remoteFile = GenerateUniqueRemoteFileName();
  4847. if (client.Exists(remoteFile))
  4848. {
  4849. client.DeleteFile(remoteFile);
  4850. }
  4851. try
  4852. {
  4853. #region Verify if merely opening the file creates a zero-byte file
  4854. using (client.Open(remoteFile, FileMode.OpenOrCreate, FileAccess.Write))
  4855. {
  4856. }
  4857. Assert.IsTrue(client.Exists(remoteFile));
  4858. var attributes = client.GetAttributes(remoteFile);
  4859. Assert.IsTrue(attributes.IsRegularFile);
  4860. Assert.AreEqual(0L, attributes.Size);
  4861. #endregion Verify if merely opening the file creates it
  4862. client.DeleteFile(remoteFile);
  4863. #region Verify if content is actually written to the file
  4864. var content = GenerateRandom(size: 100);
  4865. using (var s = client.Open(remoteFile, FileMode.OpenOrCreate, FileAccess.Write))
  4866. {
  4867. s.Write(content, offset: 0, content.Length);
  4868. }
  4869. using (var downloaded = new MemoryStream())
  4870. {
  4871. client.DownloadFile(remoteFile, downloaded);
  4872. downloaded.Position = 0;
  4873. Assert.AreEqual(CreateHash(content), CreateHash(downloaded));
  4874. }
  4875. #endregion Verify if content is actually written to the file
  4876. }
  4877. finally
  4878. {
  4879. if (client.Exists(remoteFile))
  4880. {
  4881. client.DeleteFile(remoteFile);
  4882. }
  4883. }
  4884. }
  4885. }
  4886. [TestMethod]
  4887. public void Sftp_Open_Truncate_Write_ExistingFile()
  4888. {
  4889. const int fileSize = 5 * 1024;
  4890. // use new content that contains less bytes than original content to
  4891. // verify whether file is first truncated
  4892. var originalContent = new byte[] { 0x05, 0x0f, 0x0d, 0x0a, 0x04 };
  4893. var newContent = new byte[] { 0x07, 0x03, 0x02, 0x0b };
  4894. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4895. using (var input = CreateMemoryStream(fileSize))
  4896. {
  4897. client.Connect();
  4898. var remoteFile = GenerateUniqueRemoteFileName();
  4899. if (client.Exists(remoteFile))
  4900. {
  4901. client.DeleteFile(remoteFile);
  4902. }
  4903. input.Position = 0;
  4904. try
  4905. {
  4906. client.WriteAllBytes(remoteFile, originalContent);
  4907. using (var s = client.Open(remoteFile, FileMode.Truncate, FileAccess.Write))
  4908. {
  4909. s.Write(newContent, offset: 0, newContent.Length);
  4910. }
  4911. using (var downloaded = new MemoryStream())
  4912. {
  4913. client.DownloadFile(remoteFile, downloaded);
  4914. input.Position = 0;
  4915. downloaded.Position = 0;
  4916. Assert.AreEqual(CreateHash(newContent), CreateHash(downloaded));
  4917. }
  4918. }
  4919. finally
  4920. {
  4921. if (client.Exists(remoteFile))
  4922. {
  4923. client.DeleteFile(remoteFile);
  4924. }
  4925. }
  4926. }
  4927. }
  4928. [TestMethod]
  4929. public void Sftp_Open_Truncate_Write_FileDoesNotExist()
  4930. {
  4931. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4932. {
  4933. client.Connect();
  4934. var remoteFile = GenerateUniqueRemoteFileName();
  4935. if (client.Exists(remoteFile))
  4936. {
  4937. client.DeleteFile(remoteFile);
  4938. }
  4939. try
  4940. {
  4941. Stream stream = null;
  4942. try
  4943. {
  4944. stream = client.Open(remoteFile, FileMode.Truncate, FileAccess.Write);
  4945. Assert.Fail();
  4946. }
  4947. catch (SshException)
  4948. {
  4949. }
  4950. Assert.IsFalse(client.Exists(remoteFile));
  4951. }
  4952. finally
  4953. {
  4954. if (client.Exists(remoteFile))
  4955. {
  4956. client.DeleteFile(remoteFile);
  4957. }
  4958. }
  4959. }
  4960. }
  4961. [TestMethod]
  4962. public void Sftp_OpenRead()
  4963. {
  4964. const int fileSize = 5 * 1024 * 1024;
  4965. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4966. {
  4967. client.Connect();
  4968. var remoteFile = GenerateUniqueRemoteFileName();
  4969. SftpCreateRemoteFile(client, remoteFile, fileSize);
  4970. try
  4971. {
  4972. using (var s = client.OpenRead(remoteFile))
  4973. {
  4974. var buffer = new byte[s.Length];
  4975. var stopwatch = new Stopwatch();
  4976. stopwatch.Start();
  4977. var bytesRead = s.Read(buffer, offset: 0, buffer.Length);
  4978. stopwatch.Stop();
  4979. var transferSpeed = CalculateTransferSpeed(bytesRead, stopwatch.ElapsedMilliseconds);
  4980. Console.WriteLine(@"Elapsed: {0} ms", stopwatch.ElapsedMilliseconds);
  4981. Console.WriteLine(@"Transfer speed: {0:N2} KB/s", transferSpeed);
  4982. Assert.AreEqual(fileSize, bytesRead);
  4983. }
  4984. }
  4985. finally
  4986. {
  4987. if (client.Exists(remoteFile))
  4988. {
  4989. client.DeleteFile(remoteFile);
  4990. }
  4991. }
  4992. }
  4993. }
  4994. [TestMethod]
  4995. public void Sftp_SetLastAccessTime()
  4996. {
  4997. var testFilePath = "/home/sshnet/test-file.txt";
  4998. var testContent = "File";
  4999. using var client = new SftpClient(_connectionInfoFactory.Create());
  5000. client.Connect();
  5001. using var fileStream = new MemoryStream(Encoding.UTF8.GetBytes(testContent));
  5002. var currentTime = DateTime.Now;
  5003. client.UploadFile(fileStream, testFilePath);
  5004. try
  5005. {
  5006. var time = client.GetLastAccessTime(testFilePath);
  5007. DateTimeAssert.AreEqual(currentTime.TruncateToWholeSeconds(), time);
  5008. var newTime = new DateTime(1986, 03, 15, 01, 02, 03, 123, DateTimeKind.Local);
  5009. client.SetLastAccessTime(testFilePath, newTime);
  5010. time = client.GetLastAccessTime(testFilePath);
  5011. DateTimeAssert.AreEqual(newTime.TruncateToWholeSeconds(), time);
  5012. }
  5013. finally
  5014. {
  5015. client.DeleteFile(testFilePath);
  5016. }
  5017. }
  5018. [TestMethod]
  5019. public void Sftp_SetLastAccessTimeUtc()
  5020. {
  5021. var testFilePath = "/home/sshnet/test-file.txt";
  5022. var testContent = "File";
  5023. using var client = new SftpClient(_connectionInfoFactory.Create());
  5024. client.Connect();
  5025. using var fileStream = new MemoryStream(Encoding.UTF8.GetBytes(testContent));
  5026. var currentTime = DateTime.UtcNow;
  5027. client.UploadFile(fileStream, testFilePath);
  5028. try
  5029. {
  5030. var time = client.GetLastAccessTimeUtc(testFilePath);
  5031. DateTimeAssert.AreEqual(currentTime.TruncateToWholeSeconds(), time);
  5032. var newTime = new DateTime(1986, 03, 15, 01, 02, 03, 123, DateTimeKind.Utc);
  5033. client.SetLastAccessTimeUtc(testFilePath, newTime);
  5034. time = client.GetLastAccessTimeUtc(testFilePath);
  5035. DateTimeAssert.AreEqual(newTime.TruncateToWholeSeconds(), time);
  5036. }
  5037. finally
  5038. {
  5039. client.DeleteFile(testFilePath);
  5040. }
  5041. }
  5042. [TestMethod]
  5043. public void Sftp_SetLastWriteTime()
  5044. {
  5045. var testFilePath = "/home/sshnet/test-file.txt";
  5046. var testContent = "File";
  5047. using var client = new SftpClient(_connectionInfoFactory.Create());
  5048. client.Connect();
  5049. using var fileStream = new MemoryStream(Encoding.UTF8.GetBytes(testContent));
  5050. var currentTime = DateTime.Now;
  5051. client.UploadFile(fileStream, testFilePath);
  5052. try
  5053. {
  5054. var time = client.GetLastWriteTime(testFilePath);
  5055. DateTimeAssert.AreEqual(currentTime.TruncateToWholeSeconds(), time);
  5056. var newTime = new DateTime(1986, 03, 15, 01, 02, 03, 123, DateTimeKind.Local);
  5057. client.SetLastWriteTime(testFilePath, newTime);
  5058. time = client.GetLastWriteTime(testFilePath);
  5059. DateTimeAssert.AreEqual(newTime.TruncateToWholeSeconds(), time);
  5060. }
  5061. finally
  5062. {
  5063. client.DeleteFile(testFilePath);
  5064. }
  5065. }
  5066. [TestMethod]
  5067. public void Sftp_SetLastWriteTimeUtc()
  5068. {
  5069. var testFilePath = "/home/sshnet/test-file.txt";
  5070. var testContent = "File";
  5071. using var client = new SftpClient(_connectionInfoFactory.Create());
  5072. client.Connect();
  5073. using var fileStream = new MemoryStream(Encoding.UTF8.GetBytes(testContent));
  5074. var currentTime = DateTime.UtcNow;
  5075. client.UploadFile(fileStream, testFilePath);
  5076. try
  5077. {
  5078. var time = client.GetLastWriteTimeUtc(testFilePath);
  5079. DateTimeAssert.AreEqual(currentTime.TruncateToWholeSeconds(), time);
  5080. var newTime = new DateTime(1986, 03, 15, 01, 02, 03, 123, DateTimeKind.Utc);
  5081. client.SetLastWriteTimeUtc(testFilePath, newTime);
  5082. time = client.GetLastWriteTimeUtc(testFilePath);
  5083. DateTimeAssert.AreEqual(newTime.TruncateToWholeSeconds(), time);
  5084. }
  5085. finally
  5086. {
  5087. client.DeleteFile(testFilePath);
  5088. }
  5089. }
  5090. private static IEnumerable<object[]> GetSftpUploadFileFileStreamData()
  5091. {
  5092. yield return new object[] { 0 };
  5093. yield return new object[] { 5 * 1024 * 1024 };
  5094. }
  5095. private static Encoding GetRandomEncoding()
  5096. {
  5097. var random = new Random().Next(1, 3);
  5098. switch (random)
  5099. {
  5100. case 1:
  5101. return Encoding.Unicode;
  5102. case 2:
  5103. return Encoding.UTF8;
  5104. case 3:
  5105. return Encoding.UTF32;
  5106. default:
  5107. throw new NotImplementedException();
  5108. }
  5109. }
  5110. private static byte[] GetBytesWithPreamble(string text, Encoding encoding)
  5111. {
  5112. var preamble = encoding.GetPreamble();
  5113. var textBytes = encoding.GetBytes(text);
  5114. if (preamble.Length != 0)
  5115. {
  5116. var textAndPreambleBytes = new byte[preamble.Length + textBytes.Length];
  5117. Buffer.BlockCopy(preamble, srcOffset: 0, textAndPreambleBytes, dstOffset: 0, preamble.Length);
  5118. Buffer.BlockCopy(textBytes, srcOffset: 0, textAndPreambleBytes, preamble.Length, textBytes.Length);
  5119. return textAndPreambleBytes;
  5120. }
  5121. return textBytes;
  5122. }
  5123. private static decimal CalculateTransferSpeed(long length, long elapsedMilliseconds)
  5124. {
  5125. return (length / 1024m) / (elapsedMilliseconds / 1000m);
  5126. }
  5127. private static void SftpCreateRemoteFile(SftpClient client, string remoteFile, int size)
  5128. {
  5129. var file = CreateTempFile(size);
  5130. try
  5131. {
  5132. using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read))
  5133. {
  5134. client.UploadFile(fs, remoteFile);
  5135. }
  5136. }
  5137. finally
  5138. {
  5139. File.Delete(file);
  5140. }
  5141. }
  5142. private static byte[] GenerateRandom(int size)
  5143. {
  5144. var random = new Random();
  5145. var randomContent = new byte[size];
  5146. random.NextBytes(randomContent);
  5147. return randomContent;
  5148. }
  5149. private static Stream CreateStreamWithContent(string content)
  5150. {
  5151. var memoryStream = new MemoryStream();
  5152. var sw = new StreamWriter(memoryStream, Encoding.ASCII, 1024);
  5153. sw.Write(content);
  5154. sw.Flush();
  5155. memoryStream.Position = 0;
  5156. return memoryStream;
  5157. }
  5158. private static string GenerateUniqueRemoteFileName()
  5159. {
  5160. return $"/home/sshnet/{Guid.NewGuid():D}";
  5161. }
  5162. }
  5163. }